Open
Description
What is the improvement or update you wish to see?
import { auth } from "auth"
export const GET = auth((req) => {
if (req.auth) {
return Response.json({ data: "Protected data" })
}
return Response.json({ message: "Not authenticated" }, { status: 401 })
}) as any // TODO: Fix `auth()` return type
This code is from next-auth-example template.
without explicit type casting as any
, type error occurs
such as
Type error: Route "app/api/protected/route.ts" has an invalid export:
"unknown" is not a valid POST return type:
Expected "void | Response | Promise<void | Response>", got "unknown".
For my case, I handled with explicit type casting by createing new type and interface to deal with it.
app/api/sample/route.ts
interface AuthRequest extends Request {
auth?: any
}
type NextAuthAPIRouteHandler = (req: Request) => Promise<
NextResponse<
| {
error: string
}
| {
ok: boolean
}
>
>
export const POST = auth(async function POST(request: AuthRequest) {
if (!request.auth) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
await businessLogic()
return NextResponse.json({ ok: true }, { status: 200 })
} catch (error) {
return NextResponse.json(
{ ok: false, error: 'Sending Data Failed' },
{ status: 500 }
)
}
}) as NextAuthAPIRouteHandler
Therefore, there must be docs fixed since there is no explanations about explicit type casting.
Build Error always occurs without it, so i think it needs to be fixed.
Thanks.
Is there any context that might help us understand?
Reproduction environment
System:
OS: macOS 14.6.1
CPU: (8) arm64 Apple M2
Memory: 85.50 MB / 16.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 22.0.0
npm: 10.5.1
pnpm: 9.6.0
Browsers:
Chrome: 128.0.6613.113
Safari: 17.6
Does the docs page already exist? Please link to it.
https://authjs.dev/getting-started/session-management/protecting