🚀Announcing Flightcontrol - Easily Deploy Blitz.js and Next.js to AWS 🚀
Back to Documentation Menu

Setup

Topics

Jump to a Topic

Blitz Auth with Next.js

Install @blitzjs/auth plugin with:

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

Server setup

Add the following to the blitz-server.ts file:

import { setupBlitz } from "@blitzjs/next"
import {
  AuthServerPlugin,
  PrismaStorage,
  simpleRolesIsAuthorized,
} from "@blitzjs/auth"
import { db } from "db"

const { gSSP, gSP, api } = setupBlitz({
  plugins: [
    AuthServerPlugin({
      cookiePrefix: "blitz-app-prefix",
      storage: PrismaStorage(db),
      isAuthorized: simpleRolesIsAuthorized,
    }),
  ],
})

export { gSSP, gSP, api }

The storage property is needed to handle session and user storage. You can use PrismaStorage and pass your Prisma client as in the example above. You can also define the storage methods yourself:

import { setupBlitz } from "@blitzjs/next"
import {
  AuthServerPlugin,
  PrismaStorage,
  simpleRolesIsAuthorized,
} from "@blitzjs/auth"

const { gSSP, gSP, api } = setupBlitz({
  plugins: [
    AuthServerPlugin({
      cookiePrefix: "blitz-app-prefix",
      isAuthorized: simpleRolesIsAuthorized,
      storage: {
        getSession: (handle) => redis.get(`session:${handle}`),
        createSession: (session) =>
          redis.set(`session:${handle}`, session),
        deleteSession: (handle) => redis.del(`session:${handle}`),
        // ...
      },
    }),
  ],
})

export { gSSP, gSP, api }

Here's a GitHub gist with a full Redis example.

The storage methods need to conform to the following interface:

interface SessionConfigMethods {
  getSession: (handle: string) => Promise<SessionModel | null>
  getSessions: (userId: PublicData["userId"]) => Promise<SessionModel[]>
  createSession: (session: SessionModel) => Promise<SessionModel>
  updateSession: (
    handle: string,
    session: Partial<SessionModel>
  ) => Promise<SessionModel | undefined>
  deleteSession: (handle: string) => Promise<SessionModel>
}

Client setup

Then, add the following to your blitz-client.ts file:

import { AuthClientPlugin } from "@blitzjs/auth"
import { setupClient } from "@blitzjs/next"

const { withBlitz } = setupClient({
  plugins: [
    AuthClientPlugin({
      cookiePrefix: "web-cookie-prefix",
    }),
  ],
})

export { withBlitz }

Idea for improving this page? Edit it on GitHub.