NextJS 13 not able to get auth token from cookie in server and client request
Unanswered
Asiatic Lion posted this in #help-forum
Asiatic LionOP
I have a NextJS 13 app with JWT authentication to Django backend server.
This is my home server page where I'm getting a cookie which is the access token. This page is server side.
Get access token function
This is my home server page where I'm getting a cookie which is the access token. This page is server side.
export default async function DashboardPage() {
const apiResponse = await fetch(`${BASE_API_URL}/staff/dashboard-home`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getAccessTokenCookie()}`,
},
});
const homePageResponse = await apiResponse.json();
}Get access token function
import { cookies } from "next/headers"; // Import cookies
export function getAccessTokenCookie() {
const nextCookies = cookies(); // Get cookies object
const token = nextCookies.get("access_token")?.value;
return token;
}5 Replies
Asiatic LionOP
I also have a fetch wrapper that works on client side components to get the cookie.
import { BASE_API_URL } from "@/constants/constants";
import { authService } from "@/services/auth.service";
import Cookies from "js-cookie";
type JSONValue =
| boolean
| number
| string
| null
| readonly JSONValue[]
| { readonly [key: string]: JSONValue };
export const fetchWrapper = {
get: request("GET"),
post: request("POST"),
put: request("PUT"),
delete: request("DELETE"),
patch: request("PATCH"),
};
function request(method: string) {
return async (url: string, body: JSONValue) => {
const requestHeaders = authHeader(url);
requestHeaders.append("Content-Type", "application/json");
const requestOptions: RequestInit = {
method,
headers: requestHeaders,
};
if (body) {
requestOptions.body = JSON.stringify(body);
}
try {
const response = await fetch(url, requestOptions);
return handleResponse(response);
} catch (error) {
return Promise.reject(error);
}
};
}
// helper functions
function authHeader(url: string) {
// return auth header with jwt if user is logged in and request is to the api url
const isLoggedIn = true ? Cookies.get("access_token") : false;
const isApiUrl = url.startsWith(BASE_API_URL);
let headers: HeadersInit = new Headers();
if (isLoggedIn && isApiUrl) {
headers.append("Authorization", `Bearer ${Cookies.get("access_token")}`);
}
return headers;
}
async function handleResponse(response: Response) {
const isJson = response.headers
?.get("content-type")
?.includes("application/json");
const data = isJson ? await response.json() : null;
// check for error response
if (!response.ok) {
if ([401, 403].includes(response.status)) {
// auto logout if 401 Unauthorized or 403 Forbidden response returned from api
authService.logout();
}
}
return data;
}Usage is like this:
When I try to use the same usage in a server page the cookie token is always undefined as it cannot access it. How do I modify my fetch wrapper to work with server side as well as client components?
My code is also live here - https://github.com/DarkAbhi/terrum-admin-panel
const apiResponse = await challengeService.createChallenge(
values.name,
values.description,
formatDateToISOString(values.start_date),
formatDateToISOString(values.end_date)
);
setIsLoading(false);
if (!apiResponse.error) {
router.push("/challenges");
router.refresh();
} else {
toast({
variant: "destructive",
title: "An unexpected error occured.",
});
}When I try to use the same usage in a server page the cookie token is always undefined as it cannot access it. How do I modify my fetch wrapper to work with server side as well as client components?
My code is also live here - https://github.com/DarkAbhi/terrum-admin-panel
Capelin
Assuming you want to get the JWT. The JWT is not supposed to be exposed to the client. It is supposed to only be used on the server.
Perhaps this can be of some help (even though it's an issue):
https://nextjs-forum.com/post/1152321713934192790
Perhaps this can be of some help (even though it's an issue):
https://nextjs-forum.com/post/1152321713934192790
@Capelin Assuming you want to get the JWT. The JWT is not supposed to be exposed to the client. It is supposed to only be used on the server.
Perhaps this can be of some help (even though it's an issue):
https://discord.com/channels/752553802359505017/1152321713934192790
Asiatic LionOP
This is with Next-auth, will it be the same when the token is stored in cookies on the browser?
Capelin
it should only be stored in _secure cookies, so they won't be accessed from the client. I don't think the JWT is intended to be passed as a non-secure cookie