[](https://blitzjs.com)
npm install @blitzjs/next
The @blitzjs/next adapter exposes functions & components specific for
the Next.js framework.
You can install @blitzjs/next by running the following command:
``bash`
npm i @blitzjs/next # yarn add @blitzjs/next # pnpm add @blitzjs/next
Blitz.js extends the next.config.js file by accepting a blitz
property.
`ts`
blitz?: {
resolverPath?: ResolverPathOptions;
customServer?: {
hotReload?: boolean;
};
};
For more information on setting a custom resolverPath, read more at
the RPC Specification
Inside src/blitz-client.ts:
`ts
import {setupBlitzClient} from "@blitzjs/next"
export const {withBlitz} = setupBlitzClient({
plugins: [],
})
`
Then inside src/pages/_app.tsx wrap MyApp function with thewithBlitz HOC component.
`ts
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 "src/blitz-client"
function RootErrorFallback({error}: ErrorFallbackProps) {
if (error instanceof AuthenticationError) {
return
function MyApp({Component, pageProps}: AppProps) {
return (
)
}
export default withBlitz(MyApp)
`
An provider and component is@blitzjs/next
supplied by
`ts`
setupBlitzClient({
plugins: [],
})
#### Arguments
- plugins: An array of Blitz.js plugins
- Required
#### Returns
An object with the withBlitz HOC wrapper
Inside src/blitz-server.ts
`ts
import {setupBlitzServer} from "@blitzjs/next"
export const {gSSP, gSP, api} = setupBlitzServer({
plugins: [],
})
`
`ts`
setupBlitzServer({
plugins: [],
onError?: (err) => void
})
#### Arguments
- plugins: An array of Blitz.js pluginsonError:
- Required
- Catch all errors _(Great for services like sentry)_
#### Returns
An object with the gSSP,
gSP & api wrappers.
The Blitz CLI supports running custom Next.js servers. This means you can
compile both javascript & typescript while using the Blitz.js CLI to
inject env variables. By default, the CLI checks for
src/server/index.[ts | js] or src/server.[ts | js]
For more information about custom Next.js servers, check the
official docs
All Next.js wrapper functions are serialized with
superjson. That means you can
use Date, Map, Set & BigInt when returning data. Another thing to
note is that Blitz runs the middlewares from plugins before calling the
Next.js request handler.
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.
#### getStaticProps
`ts
import {gSP} from "src/blitz-server"
export const getStaticProps = gSP(async ({ctx}) => {
return {
props: {
data: {
userId: ctx?.session.userId,
session: {
id: ctx?.session.userId,
publicData: ctx?.session.$publicData,
},
},
},
}
})
`
#### getServerSideProps
`ts
import {gSSP} from "src/blitz-server"
export const getServerSideProps = gSSP(async ({ctx}) => {
return {
props: {
userId: ctx?.session.userId,
publicData: ctx?.session.$publicData,
},
}
})
`
#### api
`ts
import {api} from "src/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_
You may want to check if the user is logged in before your page loads.
We’re going to use the getCurrentUser query insidegetServerSideProps() by calling the query directly. Then you can check
if the user is logged in on the server and use the built-in Next.js
redirect property.
`ts
import {Routes, BlitzPage} from "@blitzjs/next"
import {gSSP} from "src/blitz-server"
import getCurrentUser from "src/users/queries/getCurrentUser"
export const getServerSideProps = gSSP(async ({ctx}) => {
const currentUser = await getCurrentUser(null, ctx)
if (currentUser) {
return {
props: {
user: currentUser,
},
}
} else {
return {
redirect: {
destination: Routes.LoginPage(),
permanent: false,
},
}
}
})
`
You can set the types returned from the Next.js data fetching functions.
All Blitz.js wrappers for the Next.js functions accept a generic. Same
with the BlitzPage type.
So for example, we can use some typescript utilities to help use get the
types returned by getCurrentUser()
`ts
import {Routes, BlitzPage} from "@blitzjs/next"
import {gSSP} from "src/blitz-server"
import getCurrentUser from "src/users/queries/getCurrentUser"
type TCurrentUser = Awaited
export const getServerSideProps = gSSP<{user: TCurrentUser}>(async ({ctx}) => {
const currentUser = await getCurrentUser(null, ctx)
if (currentUser) {
return {
props: {
user: currentUser,
},
}
} else {
return {
redirect: {
destination: Routes.LoginPage(),
permanent: false,
},
}
}
})
const Page: BlitzPage<{user: TCurrentUser}> = ({user}) => { User Page {user.email}
return (
{user &&
)
}
export default Page
`
There’s an edge case where you may be throwing an error in a query that’s
being called on an initial page load, causing a server error instead of
hitting the . This is because when initially loading_app.tsx
the page, there is no ErrorBoundary component rendered until is
mounted. Though, this is expected behaviour, there is a workaround.
For an example, in a query where the user is not found you can create a
NotFoundError() then return the status code.
`ts
export default resolver.pipe(resolver.zod(GetUser), async (input) => {
const {id} = input
const user = await db.user.findFirst({where: {id}})
if (!user) {
const userError = new NotFoundError("User not found")
return {
error: userError.statusCode,
}
} else {
return {
user,
}
}
})
`
Then on the server (in this case getServerSideProps()) you can call the
query and if the error key is found in the return object then show an
error.
`ts
export const getServerSideProps = gSSP(async ({ ctx }) => {
const user = await getUser({ 1 }, ctx)
if("error" in user) {
return { props: { error: user.error}}
} else {
return { props: { user }}
}
})
`
You can also catch server errors in _app.tsx and show the errors with a
toast component.
`tsx``
function MyApp({Component, pageProps}: AppProps) {
const getLayout = Component.getLayout || ((page) => page)
if (pageProps.error) {
return
}
return (
{getLayout(
)
}