blitz-js / blitz-js/blitz

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

Open
#4,338 3 comments 0 reactions 0 assignees View on GitHub
kind/bug status/triage
Dominant language
TypeScript
Stars
14.1k
Forks
803
PR merge metrics
No merged PRs in 30d

Description

### What is the problem?

I'm following **[these docs](https://blitzjs.com/docs/auth-server#api-routes)** 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**:

```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:**

```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
7. Refresh page
8. 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_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.