-
SummaryHey everyone, I'm currently working on the frontend part of an application where I need to set an HttpOnly cookie (token) upon user login. The backend is deployed on an HTTPS server, and I'm developing the frontend locally using Next.js (running on localhost). Problem: const res = await fetch("https://backend_url.com", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
phone: form.getValues("phone"),
otp: Number(form.getValues("otp")),
}),
credentials: "include", // Including credentials to allow cookies
}); Backend: res.cookie('token', token, {
httpOnly: true,
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
sameSite: 'None', // Allow cross-origin requests
path: "/",
secure: true, // Set to 'true' for HTTPS (I also tried 'false' for testing)
}); What I've Tried: Setting credentials: 'include' on the frontend to ensure that cookies are sent along with the request. Additional Context: I’m looking for suggestions on how to keep the HttpOnly cookie from disappearing after a page reload or navigating between pages. Additional informationNo response ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 5 replies
-
i have the same issue, have you found the solution? |
Beta Was this translation helpful? Give feedback.
-
Some solution? |
Beta Was this translation helpful? Give feedback.
-
Hi, any solution on this? I am facing the same issue. Was there any solution for this? |
Beta Was this translation helpful? Give feedback.
-
Hi Aminul,
Are you making request on the same next.js server APIs or on any other
external server?
I was facing this issue with external node.js APIS.
But it got sorted out automatically as I remembered.
…On Fri, 15 Aug, 2025, 11:03 pm Aminul667, ***@***.***> wrote:
Hi, any solution on this? I am facing the same issue. Was there any
solution for this?
—
Reply to this email directly, view it on GitHub
<#71765 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/A6XF66JFERFC4BEXDMNCXET3NYKVTAVCNFSM6AAAAABQPZDAYCVHI2DSMVQWIX3LMV43URDJONRXK43TNFXW4Q3PNVWWK3TUHMYTIMJRHEZTSNI>
.
You are receiving this because you commented.Message ID: <vercel/next.
***@***.***>
|
Beta Was this translation helpful? Give feedback.
-
Node.js setup is okay;
Actually you have to create your own 2 Custom axios instances.
1-axiosServerSideInstance (for server components)
2- axiosClientInstance (for client components)
*Reason*:
when you save cookies, it is only available for server components using *const
cookieStore = await cookies(); // import { cookies } from 'next/headers';*
but for client components use have first fetch this cookie from next.js
server.(for this you will create an api in '
*api/auth/token/route.js'code for creating Custom axios instances:1-For
client side:*
import axios from 'axios';
import { BASE_URL } from '../constants';
// Create a single axios instance
const axiosClientInstance = axios.create({
baseURL: BASE_URL,
withCredentials: true, // Ensure cookies are sent if needed
});
// Add a request interceptor to fetch the token from cookies
axiosClientInstance.interceptors.request.use(async (config) => {
try {
const response = await fetch('/api/auth/token');
if (response.ok) {
const data = await response.json();
// console.log(data.token);
if (data?.token) {
config.headers.Authorization = `${data.token}`;
}
// setToken(data.token);
} else {
console.error('Failed to fetch token');
}
// const cookieStore = await cookies();
// const token = cookieStore.get('token')?.value;
} catch (error) {
console.error('Error fetching token from cookies:', error);
}
return config;
}, (error) => {
return Promise.reject(error);
});
export default axiosClientInstance;
use this (axiosClientInstance) for making requests from client components
*2-For client side:*
import axios from 'axios';
import { cookies } from 'next/headers';
import { BASE_URL } from '../constants';
// Create a single axios instance
const axiosServerInstance = axios.create({
baseURL: BASE_URL,
withCredentials: true, // Ensure cookies are sent if needed
});
// Add a request interceptor to fetch the token from cookies
axiosServerInstance.interceptors.request.use(async (config) => {
try {
const cookieStore = await cookies();
const token = cookieStore.get('token')?.value;
if (token) {
config.headers.Authorization = `${token}`;
}
} catch (error) {
console.error('Error fetching token from cookies:', error);
}
return config;
}, (error) => {
return Promise.reject(error);
});
export default axiosServerInstance;
*use this instance for making requests from server comps.*
*how to create fetchToken Api: *
write following code in 'api/auth/token/route.js'
// app/api/auth/token/route.ts
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
export async function GET() {
const cookieStore = await cookies();
const token = cookieStore.get('token')?.value;
if (!token) {
return NextResponse.json({ error: 'Token not found' }, { status: 404
});
}
return NextResponse.json({ token });
}
Now whenever you make any request on external server, *axiosServerInstance
and axiosClientInstance, *first will attach cookies in the header before
making api calls
How to make api calls:
const response = await axiosClientInstance.get(`/
course-subject-and-lessons/${courseData.CourseID}`);
const response = await axiosServerInstance.get('/course/lessonData/' +
sectionId);
This is how you can ensure that the token is included in the headers of
every request
Hope This will help
Thank You
…On Fri, 15 Aug 2025 at 23:22, Aminul667 ***@***.***> wrote:
My frontend and backend are separate. In the frontend, I have used NextJS
and axios, and in the backend, NodeJS with ExpressJS. I am facing the same
issue you have described there. It works fine in development (locally), but
it doesn't work when I host it to vercel.
This is my cors origin setup
const app: Application = express();
app.use(
cors({
origin: "https://my-frontend-domain.vercel.app",
credentials: true, // allows cookies to be sent
})
);
app.use(cookieParser());
And this is my axios instance
const axiosInstance = axios.create({
baseURL: envConfig.baseApi, // e.g.,
https://my-backend-domain.vercel.app/api/v1
withCredentials: true, // for client-side requests
headers: {
Accept: "application/json",
},
});
—
Reply to this email directly, view it on GitHub
<#71765 (reply in thread)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/A6XF66MW6BUM3J5VHKOJLOT3NYM5HAVCNFSM6AAAAABQPZDAYCVHI2DSMVQWIX3LMV43URDJONRXK43TNFXW4Q3PNVWWK3TUHMYTIMJRHE2TCNA>
.
You are receiving this because you commented.Message ID: <vercel/next.
***@***.***>
|
Beta Was this translation helpful? Give feedback.
yeah man just try to set it like this from your backend .
res.status(200).cookie("token", token, { httpOnly: true, maxAge: 7 * 24 * 60 * 60 * 1000, secure: process.env.NODE_ENV === "production", })
remove sameSite