Pass accessToken to external backend
Unanswered
Northeast Congo Lion posted this in #help-forum
Northeast Congo LionOP
how to pass accesToken to multiple server component (I'm calling external backend not using api routes) I also want to use some axios fetch call on both client and sever so what's the best approach ?
If it's a API route then it's easy with middleware
If it's a API route then it's easy with middleware
4 Replies
What auth library are you using?
Also, are you using session tokens or JWT?
Northeast Congo LionOP
next-auth
found a workaround to use api call fn on both client and server
export const createServerClient = async () => {
const session = await auth();
const accessToken = session?.user.accessToken;
return axios.create({
baseURL: env.NEXT_PUBLIC_API_BASE_URL,
headers: {
"Content-Type": "application/json",
Authorization:
},
});
};
export const apiClient = cache(async () => {
if (typeof window === "undefined") {
return createServerClient();
} else {
return spAxios;
}
});
export const createServerClient = async () => {
const session = await auth();
const accessToken = session?.user.accessToken;
return axios.create({
baseURL: env.NEXT_PUBLIC_API_BASE_URL,
headers: {
"Content-Type": "application/json",
Authorization:
Bearer ${accessToken},},
});
};
export const apiClient = cache(async () => {
if (typeof window === "undefined") {
return createServerClient();
} else {
return spAxios;
}
});