I am working on a Next.js application and facing an authentication issue when calling a protected API route from another protected API route. Additionally, I am unable to call a protected API route from a server action. Here’s a detailed explanation of the problem:
/api/get-order-detail/[id]
export async function GET(req:NextRequest){
const res = await axios.get(`${DOMAIN}/api/get-token`); // API Failure
}
/api/get-token
export async function GET(req:NextRequest){
//logic for generating token
}
/actions/get-order-detail
export const getOrderDetail = async()=>{
const res = await axios.get(`${DOMAIN}/api/get-token`); // API Failure
}
- I have two protected API routes in my Next.js application, secured
using NextAuth. - When I make a request from the client to the server, the necessary
cookies are sent along with the request, and everything works fine. - However, when I try to make a server-to-server call from one
protected API route to another, the request fails due to missing
cookies, resulting in an authentication failure.
What I Know:
- The initial client-to-server request includes all necessary cookies,
which ensures successful authentication. - The server-to-server call lacks these cookies, leading to the
authentication failure.
Logs :
{
cookies: RequestCookies{}
Authorization:'Bearer undefined'
}
What I’ve Tried:
- Manually adding cookies to the server-to-server request headers, but
I am unsure how to properly do this in Next.js. This was working in local but not in production (vercel).
How can I correctly pass authentication cookies when making server-to-server requests in a Next.js application?