Hi,
I’m using Next.js 15.4.6 with the App Router and @auth0/nextjs-auth0 ^4.9.0.
I need to access the logged-in user’s ID (sub) inside a backend API route so I can create and store an object tied to that user.
However, I can’t figure out the correct way to retrieve the session in an App Router API route.
getSession doesn’t exist on @auth0/nextjs-auth0.
Importing from @auth0/nextjs-auth0/edge throws Cannot find module.
What’s the proper way to get the user/session inside an API route when using the App Router?
Thanks!
Hi @rithvikrao2005, and welcome to the Augth0 Community!
The getSession
function does exist and is the correct one to use. You might have been looking at documentation for a different context or had a typo in your import. The correct import is import { getSession } from '@auth0/nextjs-auth0';
.
Here is an example:
import { getSession } from '@auth0/nextjs-auth0';
import { NextResponse } from 'next/server';
export async function POST(req: Request) {
const session = await getSession();
if (!session?.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userId = session.user.sub;
return NextResponse.json({ success: true, userId: userId });
}
If that still doesn’t work, try with something like this:
import { auth0 } from "@/lib/auth0";
import { NextResponse, NextRequest } from "next/server";
export async function GET(req: NextRequest) {
const session = await auth0.getSession();
if (!session?.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userId = session.user.sub;
return NextResponse.json({ ... });
}
I hope this helps you!
Teodor.