Install @blitzjs/auth
plugin with:
npm i @blitzjs/auth # yarn add @blitzjs/auth # pnpm add @blitzjs/auth
Add the following to the blitz-server.ts
file:
import { setupBlitzServer } from "@blitzjs/next"
import {
AuthServerPlugin,
PrismaStorage,
simpleRolesIsAuthorized,
} from "@blitzjs/auth"
import { db } from "db"
const { gSSP, gSP, api } = setupBlitzServer({
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 { setupBlitzServer } from "@blitzjs/next"
import {
AuthServerPlugin,
PrismaStorage,
simpleRolesIsAuthorized,
} from "@blitzjs/auth"
const { gSSP, gSP, api } = setupBlitzServer({
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>
}
Then, add the following to your blitz-client.ts
file:
import { AuthClientPlugin } from "@blitzjs/auth"
import { setupBlitzClient } from "@blitzjs/next"
const { withBlitz } = setupBlitzClient({
plugins: [
AuthClientPlugin({
cookiePrefix: "web-cookie-prefix",
}),
],
})
export { withBlitz }