NEXT AUTH: getToken() 'next-auth/jwt' returning null on an api endpoint
Unanswered
Colombian fino hound posted this in #help-forum
Colombian fino houndOP
I am trying to append the jwt token as an authorization header from the api route to make requests to an external server.
As per the documentations
const token = await getToken({ req }); should give me the token object. But i am receiving a null value.
Any help will be really appreciated
As per the documentations
const token = await getToken({ req }); should give me the token object. But i am receiving a null value.
import axios from 'axios';
import type { NextApiRequest, NextApiResponse } from 'next';
import { getToken } from 'next-auth/jwt';
const instance = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
});
const getReqUrl = (url: string): string | null => {
if (url.indexOf(`api/server/`) !== -1) {
return url.replace(`api/server/`, ``);
}
return null;
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
try {
const reqUrl = getReqUrl(req.url as string);
if (!reqUrl) {
throw new Error('Invalid request URL');
}
const token = await getToken({ req });
console.log(token);
if (token) {
instance.defaults.headers.common[
'Authorization'
] = `Bearer ${token.accessToken}`;
}
const response = await instance.request({
method: req.method,
url: reqUrl,
data: req.body,
params: req.query,
});
console.log(response.status);
// Pass the response data and status code to the client
res.status(response.status).json(response.data);
} catch (error) {
res.status(500).json({
data: null,
message: (error as Error)?.message??'Something went wrong. Please try again later',
});
}
}Any help will be really appreciated
7 Replies
Blue orchard bee
Did you figure it out?
the TIP in the official doc says like this
You can use the getToken() helper function in any application as long as you set the NEXTAUTH_URL environment variable and the application is able to read the JWT cookie (e.g. is on the same domain).
you might wanna invoke the API using cURL command along with a JWT cookie to nail down the culprit.
curl -v http://localhost:3000/my-api-auth -H 'Cookie: next-auth.session-token=794...or generate from Chrome Dev tool.
Colombian fino houndOP
Thank you for the response. Yeah kind of seems like an issue with the cookies. Do you have any recommendations as to how we can use axios to add those. Essentially the problem lies in making the axios instance work for both client and server requests. I am using the next api endpoint like a proxy to append the authorization header to make an external request. Would be nice if i could use axios.
im not so familiar with axios. do u want to stick with axios? actually axios does not work in Edge Runtime, so you might want to use fetch if you host on Vercel platform, take advantage of Edge especially reverse proxy is I/O bound operation, no CPU consumption.