blitz-js / blitz

⚡️ The Missing Fullstack Toolkit for Next.js

Home Page:https://Blitzjs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Blitz Auth: Blitz CTX session not populated in api route called from Next.js middleware

ourmaninamsterdam opened this issue · comments

What is the problem?

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 is not populated. The query getCurrentUser(), called from a component, returns the data as expected.

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.

Paste all your error logs here:

None

Paste all relevant code snippets here:

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?

  1. Clone https://github.com/ourmaninamsterdam/blitzjs-auth-example/
  2. npm i
  3. npm run dev
  4. Go to http://localhost:3000
  5. Hit Sign Up and create an account
  6. Refresh page
  7. Check terminal

Given you're now signed in I would expect the session to be populated with the signed in session data, but it's outputting: ctx.session { userId: null, publicData: { userId: null } }

It's populating the userId on the client from queries without issue.

Run blitz -v and paste the output here:

Blitz version: 2.0.6 (local)
macOS Monterey | darwin-arm64 | Node: v18.12.1
 Package manager: npm

  System:
    OS: macOS 12.6
  Binaries:
    Node: 18.12.1 - ~/.asdf/installs/nodejs/18.12.1/bin/node
    Yarn: Not Found
    npm: 8.19.2 - ~/.asdf/plugins/nodejs/shims/npm
  npmPackages:
    @blitzjs/auth: 2.0.6 => 2.0.6
    @blitzjs/next: 2.0.6 => 2.0.6
    @blitzjs/rpc: 2.0.6 => 2.0.6
    @prisma/client: 4.6.1 => 4.6.1
    blitz: 2.0.6 => 2.0.6
    next: 13.5.4 => 13.5.4
    prisma: 4.6.1 => 4.6.1
    react: 18.2.0 => 18.2.0
    react-dom: 18.2.0 => 18.2.0
    typescript: ^4.8.4 => 4.9.5

Please include below any other applicable logs and screenshots that show your problem:

No response

I tried the same with an App router project as well and saw the same. Is my implementation/understanding of the api handler exported from blitz-server.ts wrong? Or is this a bug?

As all I want to do is check the auth status (against ctx.session.userId or ctx.session.$isAuthorized) in the API route and return that to the Next.js middleware, we can then chooser to redirect if they're unauthorized.

Calling the api route from a component returns the correct data, it's just from middleware there's an issue.

Work in #4341 will fix this

Work in #4341 will fix this

@siddhsuresh Been following your changes in #4341 - Will these changes apply to both pages and app router API routes?