How to implement Dynamic Route Segments with Auth Beta
What is the improvement or update you wish to see?
I can't find how to implement Dynamic routes with the latest beta of authjs
Is there any context that might help us understand?
with auth handlers it only accept reqeust as params
export const GET = auth(async (req) => {
const session = req.auth;
if (!session) {
return Response.json({ error: 'Unauthorized' });
}
});
With next handlers
app/api/[slug]/route.ts
export async function GET(
request: Request,
{ params }: { params: { slug: string } }
) {
const slug = params.slug // 'a', 'b', or 'c'
}
Does the docs page already exist? Please link to it.
No response
I have the same question. Is it possible or not yet ?
I don't think so. I grab the URL from the request then split It
It seems that the type of auth() is incorrect.
Since it passes second argument to the callback, I overrode the type as this and it works 👍
import NextAuth, {
Session,
NextAuthResult as _NextAuthResult,
} from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { AppRouteHandlerFn } from 'next/dist/server/future/route-modules/app-route/module.js';
import { NextRequest } from 'next/server';
export interface NextAuthRequest extends NextRequest {
auth: Session | null;
}
const nextAuth = NextAuth({
providers: [GoogleProvider],
});
export const {
handlers: { GET, POST },
signIn,
signOut,
} = nextAuth;
export const auth = nextAuth.auth as _NextAuthResult['auth'] &
((
...args: [
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(req: NextAuthRequest, context: any) => ReturnType<AppRouteHandlerFn>,
]
) => AppRouteHandlerFn);
FWIW, I agreed with the previous workaround, but it doesn't build for me in Next. The handlers return "unknown" and Next type checking is unhappy when it looks at my route handlers.
This worked for me.
import { NextRequest } from "next/server";
import { AppRouteHandlerFn } from "next/dist/server/future/route-modules/app-route/module.js";
export interface NextAuthRequest extends NextRequest {
auth: Session | null;
}
export const auth = nextAuth.auth as typeof nextAuth.auth &
(<HandlerResponse extends Response | Promise<Response>>(
...args: [
(
req: NextAuthRequest,
context: { params: Record<string, string | string[] | undefined> }
) => HandlerResponse
]
) => (
req: Parameters<AppRouteHandlerFn>[0],
context: Parameters<AppRouteHandlerFn>[1]
) => HandlerResponse);
Then my routes had to look like this.
export const PATCH = auth(
async (
req: NextAuthRequest,
{ params }: { params: Record<string, string | string[] | undefined> }
): Promise<NextResponse> => {
// ... now I can use request.auth
})
I suspect there's a nicer way, but it unblocked me.
I've opened a PR to fix the typescript types: https://github.com/nextauthjs/next-auth/pull/10624