@blitzjs/next

中文文档
3.0.2发布于 2025/09/11MITTypeScriptESM + CJS近 30 天下载 6.3万

Blitz.js

原始使用文档
文档目录18 节
  1. Blitzjs Website
  2. GitHub
  3. Overview
  4. Setup
  5. Next Config
  6. Client
  7. Example
  8. API
  9. Server
  10. Example
  11. API
  12. Custom Server
  13. Wrappers
  14. Examples
  15. Concepts
  16. Authenticate user before page loads
  17. Return types when data fetching on the server
  18. Handling errors on initial page load

Blitz.js


Blitz Adapter for Next.js


Blitzjs Website

GitHub

Overview

The @blitzjs/next adapter exposes functions & components specific for the Next.js framework.

Setup

You can install @blitzjs/next by running the following command:

npm i @blitzjs/next # yarn add @blitzjs/next # pnpm add @blitzjs/next

Next Config

Blitz.js extends the next.config.js file by accepting a blitz property.

blitz?: {
  resolverPath?: ResolverPathOptions;
  customServer?: {
      hotReload?: boolean;
  };
};
For more information on setting a custom `resolverPath`, read more at the [RPC Specification](/docs/rpc-specification#url)

Client

Example

Inside src/blitz-client.ts:

import {setupBlitzClient} from "@blitzjs/next"

export const {withBlitz} = setupBlitzClient({
  plugins: [],
})

Then inside src/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 "src/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 `` provider and `` component is supplied by `@blitzjs/next`

API

setupBlitzClient({
  plugins: [],
})

Arguments

  • plugins: An array of Blitz.js plugins
    • Required

Returns

An object with the withBlitz HOC wrapper

Server

Example

Inside src/blitz-server.ts

import {setupBlitzServer} from "@blitzjs/next"

export const {gSSP, gSP, api} = setupBlitzServer({
  plugins: [],
})

API

setupBlitzServer({
  plugins: [],
  onError?: (err) => void
})

Arguments

  • plugins: An array of Blitz.js plugins
    • Required
  • onError: Catch all errors (Great for services like sentry)

Returns

An object with the gSSP, gSP & api wrappers.

Custom Server

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

Wrappers

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](/docs/auth).

Examples

getStaticProps

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

import {gSSP} from "src/blitz-server"

export const getServerSideProps = gSSP(async ({ctx}) => {
  return {
    props: {
      userId: ctx?.session.userId,
      publicData: ctx?.session.$publicData,
    },
  }
})

api

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

Concepts

Authenticate user before page loads

You may want to check if the user is logged in before your page loads. We’re going to use the getCurrentUser query inside getServerSideProps() 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.

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,
      },
    }
  }
})

Return types when data fetching on the server

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()

import {Routes, BlitzPage} from "@blitzjs/next"
import {gSSP} from "src/blitz-server"
import getCurrentUser from "src/users/queries/getCurrentUser"

type TCurrentUser = Awaited<ReturnType<typeof getCurrentUser>>

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}) => {
  return (
    <Layout title="Page">
      <div className="container">
        <p>User Page</p>
        {user && <p>{user.email}</p>}
      </div>
    </Layout>
  )
}

export default Page

Handling errors on initial page load

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 <ErrorBoundary />. This is because when initially loading the page, there is no ErrorBoundary component rendered until _app.tsx 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.

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.

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.

function MyApp({Component, pageProps}: AppProps) {
  const getLayout = Component.getLayout || ((page) => page)
  if (pageProps.error) {
    return <ToastComponent>{pageProps.error.statusCode}</ToastComponent>
  }
  return (
    <ErrorBoundary FallbackComponent={RootErrorFallback}>
      {getLayout(<Component {...pageProps} />)}
    </ErrorBoundary>
  )
}

版本与发布记录

@blitzjs/next 共发布 311 个版本,首次发布于 2021/04/06;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.0.2latest2025/09/111.2 年前
2.2.42025/09/111.2 年前
2.2.32025/03/031.7 年前
3.0.12025/02/241.7 年前
2.2.22025/02/241.7 年前
3.0.02025/02/211.7 年前

其他发布通道:danger → 2.0.0-danger.67,alpha → 2.0.0-alpha.71,next--a78bd33 → 0.0.0-a78bd33-20230114151431,next--next-auth → 0.0.0-next-auth-20230116170805,next--multiple-fields → 0.0.0-multiple-fields-20230207144902,next--app-dir → 0.0.0-app-dir-20230217182624。

关于 @blitzjs/next 的常见问题

如何安装 @blitzjs/next?

在项目目录运行 npm install @blitzjs/next,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:blitz(3.0.2)、next(*)、react(*)、tslog(4.9.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@blitzjs/next 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@blitzjs/next 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@blitzjs/next 可以商用吗?

@blitzjs/next 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@blitzjs/next 的下载量有多少?

根据 npm 官方下载统计,@blitzjs/next 在 2026/10/09 – 2026/11/07 这 30 天内被下载 63,162 次,日均约 2,105 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@blitzjs/next 还在维护吗?

最新版本 3.0.2 发布于 2025/09/11(1.2 年前);至今共发布 311 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/04/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。