I’m following these docs and I’m trying to add an API route that can access the user session data from Blitz CTX from an API route from Next.js middleware, but the session doesn’t get populated, even though there is a authorised session. If I use the getCurrentUser()
query from a component the correct session data is returned.
My intention is to create auth middleware to redirect a user if they don’t have a valid userId and role. My preference was to handle this on the server rather than redirecting on the client using a hook or Page.authenticate
.
Given that you’re signed in at this point, I would expect the session to be populated with the signed in session data, but the session returns: { userId: null }
.
This is a basic replication of my issue:
Middleware: /src/middleware.ts:
import { NextRequest, NextResponse } from "next/server"
export async function middleware(req: NextRequest, res: NextResponse) {
const response = await fetch(new URL("/api/auth", req.nextUrl.origin), {})
const data = await response.json()
console.log("ctx.session", data)
NextResponse.next()
}
API route from /src/pages/api/auth/index.ts:
import { api } from "src/blitz-server"
export default api(async (_req, res, ctx) => {
const publicData = ctx.session.$publicData
res.status(200).json({
userId: ctx.session.userId,
publicData: { ...publicData },
})
})
What are detailed steps to reproduce this?
- Clone https://github.com/ourmaninamsterdam/blitzjs-auth-example/
- npm i
- npm run dev
- Go to http://localhost:3000
- Hit Sign Up and create an account
- Refresh page
- Check terminal