getSession finds no user inside a Next.js API route
getSession() returns null inside pages/api even though the user is signed inShort answer
getSession is meant for the browser and does an extra fetch when used on the server. In an API route, call getServerSession with the request, response and your authOptions. In Server Components pass only authOptions. With Auth.js v5 there is one call for all of these: auth().
Fix it fast
1Find out which cause you have
Check which auth package and which session call the route uses. The fix depends on the major version.
grep -n "next-auth\|\"@auth/" package.json; grep -rn "getSession\|getServerSession\|auth()" pages app lib2Match what you see, then jump to its fix
- 1
The route imports getSession from next-auth/reactgetSession is called on the serverFix - 2
Server Component or route.ts passes req and res, or leaves authOptions outThe App Router call uses the Pages Router signatureFix - 3
package.json lists next-auth 5 or @auth/core, and the code still imports getServerSessionThe project moved to Auth.js v5, where those helpers are goneFix
- 1
What does the error look like?
getSession() returns null inside pages/api even though the user is signed inAn API route that checks the session answers 401 for a signed-in user
Cause 1 of 3
getSession is called on the server
1Check
The docs describe getSession as a client-side call and recommend getServerSession on the server, which avoids an unnecessary fetch.
grep -rn "from \"next-auth/react\"\|from 'next-auth/react'" pages/api app/api2Fix
Use getServerSession with the request, response and the same authOptions you gave NextAuth.
import { getServerSession } from 'next-auth/next'
import { authOptions } from './auth/[...nextauth]'
export default async function handler(req, res) {
const session = await getServerSession(req, res, authOptions)
if (!session) {
return res.status(401).json({ message: 'You must be logged in.' })
}
return res.json({ message: 'Success' })
}3Verify
Call the route with the session cookie and check you no longer get 401.
curl -i -H "Cookie: <your session cookie>" http://localhost:3000/api/protectedConfirmed by next-auth.js.org
Cause 2 of 3
The App Router call uses the Pages Router signature
1Check
In Server Components the documented form takes only the options object. getServerSession returns null when no one is signed in.
grep -rn "getServerSession(" app2Fix
Pass authOptions only.
import { getServerSession } from 'next-auth/next'
import { authOptions } from '@/lib/auth'
export default async function Page() {
const session = await getServerSession(authOptions)
return <pre>{JSON.stringify(session, null, 2)}</pre>
}3Verify
Reload the page while signed in and read the printed session.
npm run devConfirmed by next-auth.js.org
Cause 3 of 3
The project moved to Auth.js v5, where those helpers are gone
1Check
The v5 migration guide says to use auth() instead of getServerSession, getSession, withAuth and getToken. It also says the variables use the AUTH_ prefix, and AUTH_SECRET is the only one really required.
grep -rn "AUTH_SECRET\|NEXTAUTH_SECRET" .env* 2>/dev/null | sed 's/=.*/=<hidden>/'2Fix
Export auth from your auth.ts file and call it in the route or component. In a Pages Router API route pass req and res.
import { auth } from '@/auth'
export default async function handler(req, res) {
const session = await auth(req, res)
if (!session) return res.status(401).end()
res.json({ user: session.user })
}3Verify
Request the route signed in and signed out and compare the results.
curl -i http://localhost:3000/api/protectedConfirmed by authjs.dev
How do I stop it coming back?
- Keep authOptions (or the Auth.js config) in one file that both the handler and the pages import.
- Use getSession or useSession only in client code.
- When upgrading to v5, search the project for the old helper names in one pass.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Web apps
Apollo Server rejects a request as a potential CSRF
HTTP 400 Bad Request from the GraphQL endpoint
Apollo Server's CSRF prevention is on by default.
3 causes, each with a fixWeb apps
Clerk cannot read its publishable key in a Next.js app
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY is undefined
Clerk reads NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY.
3 causes, each with a fixWeb apps
The shell cannot find create-next-app
command not found: create-next-app
create-next-app is not meant to be installed as a shell command.
2 causes, each with a fixWeb apps
ESLint fails with: Cannot find module 'next/babel'
ESLint stops on the first file with a Babel or parser error instead of listing lint results
next/babel is a Babel preset that ships inside the next package.
3 causes, each with a fixWeb apps
Firebase Auth says the API key is not valid
Firebase: Error (auth/api-key-not-valid.-please-pass-a-valid-api-key.)
The apiKey your app sends is either empty, wrong, or blocked.
4 causes, each with a fixWeb apps
Jest fails with SyntaxError: Unexpected token when testing a Next.js component
Jest failed to parse a file.
Jest only understands plain JavaScript until a transform and a few file mappings tell it more.
3 causes, each with a fix