Session is null in Nextjs 15 middleware (Express backend) only in prod

Hi guys, I am able to get session in middleware with nodejs runtime in my dev server, but when I deploy in production it doesn't seem to pass any cookies when I make the request to the expressjs auth server.. What is the issue? Here's my middleware.ts
import { NextRequest, NextResponse } from "next/server"
import { headers } from "next/headers"
import { authClient } from "@/lib/auth"

export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl

const nextHeaders = await headers()

const session = await authClient.getSession({
fetchOptions: {
headers: nextHeaders,
},
})

console.log({ session })

if (pathname.startsWith("/dashboard") && !session.data) {
return NextResponse.redirect(new URL("/login", request.url))
}
return NextResponse.next()
}

export const config = {
runtime: "nodejs",
matcher: ["/dashboard/:path*"],
}
import { NextRequest, NextResponse } from "next/server"
import { headers } from "next/headers"
import { authClient } from "@/lib/auth"

export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl

const nextHeaders = await headers()

const session = await authClient.getSession({
fetchOptions: {
headers: nextHeaders,
},
})

console.log({ session })

if (pathname.startsWith("/dashboard") && !session.data) {
return NextResponse.redirect(new URL("/login", request.url))
}
return NextResponse.next()
}

export const config = {
runtime: "nodejs",
matcher: ["/dashboard/:path*"],
}
6 Replies
sebastian
sebastian2w ago
don't use authclient in server routes, especially the middleware dont fetch you database in the middleware use the cookie helper for the middleware provided by betterauth
nosovandriy
nosovandriy2w ago
I tried using getSessionCookie() or getCookieCache() in the middleware, but they always return null.
sebastian
sebastian2w ago
have you set different cookie names, e.g. have you customised the cookie in any way? are you following exactly what the docs say?
sebastian
sebastian2w ago
also, if you only have null session in production, then it could be a cors issue if you have a separate backend server
Rafiul
RafiulOP2w ago
Yes I'm experiencing the same. It is null on production. What cors policy should I add in the request?

Did you find this page helpful?