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.
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 ✨
export default defineEventHandler(() => {
return toSuperJSON({ date: new Date() })
})
<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>
const superApiFetch = $fetch.create({
parseResponse: fromSuperJSON,
headers: { Authorization: `Bearer ${token}` }
})
const data = await superApiFetch('/api')
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')
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