I been implementing next-auth (credentials) in a NextJS 14 project (using app router) but I’m facing a problem to secure an api route src/app/api/user/route.ts
following the Next-Auth migration guide:
<code>import { auth } from '@/auth';
import { NextApiRequest, NextApiResponse } from 'next';
import { NextResponse } from 'next/server';
export async function GET(request: NextApiRequest, response: NextApiResponse) {
const session = await auth(request, response);
if (session) {
return NextResponse.json({ message: 'test' }, { status: 200 });
}
return NextResponse.json({ message: 'Auth session fail' }, { status: 401 });
}
</code>
<code>import { auth } from '@/auth';
import { NextApiRequest, NextApiResponse } from 'next';
import { NextResponse } from 'next/server';
export async function GET(request: NextApiRequest, response: NextApiResponse) {
const session = await auth(request, response);
if (session) {
return NextResponse.json({ message: 'test' }, { status: 200 });
}
return NextResponse.json({ message: 'Auth session fail' }, { status: 401 });
}
</code>
import { auth } from '@/auth';
import { NextApiRequest, NextApiResponse } from 'next';
import { NextResponse } from 'next/server';
export async function GET(request: NextApiRequest, response: NextApiResponse) {
const session = await auth(request, response);
if (session) {
return NextResponse.json({ message: 'test' }, { status: 200 });
}
return NextResponse.json({ message: 'Auth session fail' }, { status: 401 });
}
The problem is with session
because auth()
always return an object, even if no session exist; that always return a 200 and ok response.
In the example of the migration document, auth() should return a null if not session exist.
Do you have any idea how to secure API Routes in next 14 using next-auth 5?
Thanks in advance!