`NextApiRequest` & `NextApiResponse` into App router mode
Answered
Brown Shrike posted this in #help-forum
Brown ShrikeOP
Is it possible to use
NextApiRequest
& NextApiResponse
into the App router mode?Answered by Brown Shrike
By reading the code, I realized that in NextAuth v5 we can pass a function to the
So the solution is the following:
auth
function and it returns an AppRouterHandlerFn
and in that callback, I have access to a request which is a NextAuthRequest
So the solution is the following:
// In app API Routes
import { NextAuthRequest } from "node_modules/next-auth/lib";
import { auth } from "@/auth";
export const GET = auth(
async (req: NextAuthRequest): Promise<NextResponse<ResponseData>> => {
const session = req.auth
NextResponse.json({ userEmail: session?.user.email })
}
);
2 Replies
Brown ShrikeOP
Here's a bit of context,
Using
But with the current App router mode, it looks like there's no way to pass those properties (
Using
NextAuth
, we had a way to pass the Request and the Response to the Auth as follows:// #### In API Routes
//
title="pages/api/protected.ts"
import { auth } from "../auth"
import type { NextApiRequest, NextApiResponse } from "next"
export default async (req: NextApiRequest, res: NextApiResponse) => {
const session = await auth(req, res)
if (session) {
// Do something with the session
return res.json("This is protected content.")
}
res.status(401).json("You must be signed in.")
}
But with the current App router mode, it looks like there's no way to pass those properties (
NextApiRequest
& NextApiResponse
)Brown ShrikeOP
By reading the code, I realized that in NextAuth v5 we can pass a function to the
So the solution is the following:
auth
function and it returns an AppRouterHandlerFn
and in that callback, I have access to a request which is a NextAuthRequest
So the solution is the following:
// In app API Routes
import { NextAuthRequest } from "node_modules/next-auth/lib";
import { auth } from "@/auth";
export const GET = auth(
async (req: NextAuthRequest): Promise<NextResponse<ResponseData>> => {
const session = req.auth
NextResponse.json({ userEmail: session?.user.email })
}
);
Answer