The @blitzjs/next
adapter exposes functions & components specific for
the Next.js framework.
You can install @blitzjs/next
by running the following command:
npm i @blitzjs/next # yarn add @blitzjs/next # pnpm add @blitzjs/next
Inside app/blitz-client.ts
:
import { setupBlitzClient } from "@blitzjs/next"
export const { withBlitz } = setupBlitzClient({
plugins: [],
})
Then inside pages > _app.tsx
wrap MyApp
function with the withBlitz
HOC component.
import {
ErrorFallbackProps,
ErrorComponent,
ErrorBoundary,
} from "@blitzjs/next"
import { AuthenticationError, AuthorizationError } from "blitz"
import type { AppProps } from "next/app"
import React, { Suspense } from "react"
import { withBlitz } from "app/blitz-client"
function RootErrorFallback({ error }: ErrorFallbackProps) {
if (error instanceof AuthenticationError) {
return <div>Error: You are not authenticated</div>
} else if (error instanceof AuthorizationError) {
return (
<ErrorComponent
statusCode={error.statusCode}
title="Sorry, you are not authorized to access this"
/>
)
} else {
return (
<ErrorComponent
statusCode={(error as any)?.statusCode || 400}
title={error.message || error.name}
/>
)
}
}
function MyApp({ Component, pageProps }: AppProps) {
return (
<ErrorBoundary FallbackComponent={RootErrorFallback}>
<Component {...pageProps} />
</ErrorBoundary>
)
}
export default withBlitz(MyApp)
An <ErrorBoundary />
provider and <ErrorComponent />
component is supplied by @blitzjs/next
setupBlitzClient({
plugins: []
})
plugins:
An array of blitzjs pluginsAn object with the withBlitz
HOC wrapper
Inside app > blitz-server.ts
import { setupBlitzServer } from "@blitzjs/next"
export const { gSSP, gSP, api } = setupBlitzServer({
plugins: [],
})
The gSSP
, gSP
& api
functions all pass down the context of the
session if you're using the auth plugin. Read more about the auth plugin
here @blitzjs/auth.
setupBlitzServer({
plugins: [],
onError?: (err) => void
})
plugins:
An array of blitzjs pluginsonError:
Catch all errors (Great for services like sentry)An object with the gSSP
, gSP
& api
wrappers.
import { gSP } from "app/blitz-server"
export const getStaticProps = gSP(async ({ ctx }) => {
return {
props: {
data: {
userId: ctx?.session.userId,
session: {
id: ctx?.session.userId,
publicData: ctx?.session.$publicData,
},
},
},
}
})
import { gSSP } from "app/blitz-server"
export const getServerSideProps = gSSP(async ({ ctx }) => {
return {
props: {
userId: ctx?.session.userId,
publicData: ctx?.session.$publicData,
},
}
})
import { api } from "app/blitz-server"
export default api(async (req, res, ctx) => {
res.status(200).json({ userId: ctx?.session.userId })
})
For more information about Next.js API routes, visit their docs at https://nextjs.org/docs/api-routes/introduction