nuxt-superjson
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

npm version npm downloads License Nuxt

Welcome to Nuxt SuperJSON! 👋

Nuxt already provides a tRPC-like connection between the frontend and backend, but it has limitations when handling rich types. Typically, developers define Payload reducers and reviver plugins for each custom type or class. However, these plugins only revive data on the first page load, making subsequent fetches inconsistent.

To simplify this process, we introduce utilities that handles SuperJSON serialization for API endpoints using toSuperJSON, along with response deserialization via fromSuperJSON.

Additionally, we've created $superFetch and useSuperFetch to handle fetch deserialization seamlessly. This keeps your code D-R-Y and effortless, allowing you to focus on building features instead of dealing with data inconsistencies.

Quick Setup

Install the module to your Nuxt application with one command:

npx nuxi module add nuxt-superjson

That's it! You can now use SuperJSON in your Nuxt app ✨

Implementation

Serialize API responses with toSuperJSON

export default defineEventHandler(() => {
  return toSuperJSON({ date: new Date() })
})

Retrieve deserialized SuperJSON data

<template>
  <pre>
    {{ data }}
    {{ data.date instanceof Date }} // true
  </pre>
</template>

<script lang="ts" setup>
// useFetch approach
const { data } = await useSuperFetch('/api')

// $fetch approach
const { $superFetch } = useNuxtApp()
const data = await $superFetch('/api')
</script>

Recipes

Custom $fetch with fromSuperJSON

const superApiFetch = $fetch.create({
  parseResponse: fromSuperJSON,
  headers: { Authorization: `Bearer ${token}` }
})

const data = await superApiFetch('/api')

Custom useFetch with fromSuperJSON

const useSuperApiFetch: typeof useFetch = <T>(
  req: Parameters<typeof useFetch<T>>[0],
  opts: Parameters<typeof useFetch<T>>[1],
) => useFetch(req, { ...opts, $fetch: superApiFetch })

const { data } = await useSuperApiFetch('/api')

Contribution

Local development
# Install dependencies
npm install

# Generate type stubs
npm dev:prepare

# Develop with the playground
npm dev

# Build the playground
npm dev:build

# Run ESLint
npm lint
npm lint:fix

# Run Prettier
npm prettier
npm prettier:fix

# Run Vitest
npm test
npm test:watch

# Release new version
npm release

Made with ❤️ by @germondai

Readme

Keywords

none

Package Sidebar

Install

npm i nuxt-superjson

Weekly Downloads

12

Version

1.0.0

License

MIT

Unpacked Size

9.05 kB

Total Files

19

Last publish

Collaborators

  • germondai