I’m working with Next.js and using JWT tokens for authentication. After logging in, I set the token in cookies. It works perfectly on localhost, but after deployment on the server, it’s not functioning as expected. It works fine on the domain when using “use client,” but not with “use server.”
Any suggestions?
Is there any implementation from backend just like cors?
i m sharing code with dummy api url
Working code in localstorage
"use server";
import { cookies } from "next/headers";
import Details from "../Account-Closure/details";
const fetchDummyDataWithToken = async () => {
try {
const cookieStore = cookies(); // Direct call without await
const token = (await cookieStore).get("token")?.value;
if (!token) {
throw new Error("Token not found in cookies");
}
const response = await fetch(
"https://api.co.in",
{
method: "GET",
headers: {
Authorization: Bearer ${token},
"Content-Type": "application/json", // Optional: add content type
},
}
);
if (!response.ok) {
throw new Error(Failed to fetch data. Status: ${response.status});
}
return response.json();
} catch (error) {
console.error("Error fetching data:", error);
return null;
}
};
const DummyApiPage = async () => {
const apiResponse = await fetchDummyDataWithToken();
if (!apiResponse) {
return <div>Error fetching data. Please try again later.</div>;
}
console.log(apiResponse);
const { result, data } = apiResponse;
const { basic_details, dp_details } = data;
return (
<div style={{ padding: "20px", fontFamily: "Arial" }}>
<h1>API Response</h1>
<pre>{JSON.stringify(apiResponse, null, 2)}</pre>
<section>
<h2>Result</h2>
<p>Flag: {result.flag}</p>
<p>Message: {result.flag_message}</p>
</section>
<section>
<h2>Basic Details</h2>
<ul>
<li>UCC Code: {basic_details.ucc_code}</li>
<li>PAN: {basic_details.pan}</li>
<li>Account Status: {basic_details.account_status}</li>
<li>Date of Birth: {basic_details.date_of_birth}</li>
</ul>
</section>
{/* DP Details Section */}
<section>
<h2>DP Details</h2>
<ul>
{dp_details.map((dp: any, index: any) => (
<li key={index}>
<strong>Depository:</strong> {dp.depository} <br />
<strong>BO ID:</strong> {dp.bo_id} <br />
<strong>Client ID:</strong> {dp.client_id} <br />
<strong>Status:</strong> {dp.dp_status} <br />
<strong>Primary Flag:</strong> {dp.primary_flag}
</li>
))}
</ul>
</section>
</div>
// <>adasdahsdahsd</>
);
};
export default DummyApiPage;
0
This is how i have done in multiple projects
create a helper file for server only
srcserverhelper.ts
import 'server-only';
export enum COOKIES {
JWT = 'token',
RESEND_OTP_JWT = 'resend-otp-token',
ACCEPT_COOKIES_POLICY = 'acceptCookies',
}
export const setSecureJwt = (tkn: string) => {
cookies().set(COOKIES.JWT, tkn, {
secure: true,
httpOnly: true,
sameSite: true,
});
};
export const getAuthorizationHeader = () => {
const token = cookies().get(COOKIES.JWT)?.value;
if (!token) return false;
return { Authorization: 'Bearer ' + token };
};
then create server action for login
srcserveractionsauth.actions.ts
// You can generate this token, or you can get it
// from your backend server in case your backend is on another
// server and then call the helper function
setSecureJwt(jwt);
Create a data-lib for tours and there you can use getAuthorizationHeader
helper
function
srcserverdata-libtour.data-lib.ts
import 'server-only';
import { Roles } from '@/enums';
import { REQUEST_METHODS } from '@/server/enums/shared';
import {
getAuthorizationHeader,
getNodeRequiredRequestHeaders,
getCacheKey,
} from '@/server/helper';
import { getServerError } from '@/server/server-error';
import { APIResponse, ToursDetailsType } from '@/types';
import { createTourRequestURL } from '@/util';
export const getTourRequests = async (
currentPage: number,
role: Roles,
propertyId?: string
) => {
const url = createTourRequestURL(currentPage, role, propertyId);
const res: Response = await fetch(url, {
method: REQUEST_METHODS.GET,
headers: {
...getNodeRequiredRequestHeaders(),
...getAuthorizationHeader(),
},
next: { tags: [getCacheKey('toursTable')] },
});
if (res.status === 404) {
return {
data: [],
pages: 1,
results: 0,
totalDocs: 0,
} as APIResponse<ToursDetailsType>;
}
if (!res.ok) {
throw await getServerError(res);
}
return res.json() as Promise<APIResponse<ToursDetailsType>>;
};
and then in the server compeont you can use the helper function from data-lib
import React from 'react';
import ToursTable from '@/components/ui/ToursTable';
import { Roles } from '@/enums';
import { getTourRequests } from '@/server/data-lib';
export default async function TableWrapper({
currentPage,
}: {
currentPage: number;
}) {
const tourRequests = await getTourRequests(currentPage, Roles.TENANT);
return (
<ToursTable
currentPage={currentPage}
data={tourRequests.data}
totalDocs={tourRequests.totalDocs}
/>
);
}
1