Update cookies when request is made from the server
Unanswered
CodigoK 401 posted this in #help-forum
I am trying to set the cookies after refreshing the token. The problem is that it never sets. I am using Set-Cookie from my api in express.
55 Replies
it is worth mentioning that the request is being made from the server.
Provide some example code of what your trying to do please π
headers
Object [AxiosHeaders] {
'x-powered-by': 'Express',
'access-control-allow-origin': 'http://localhost:3000',
'access-control-allow-headers': 'x-auth-token, Origin, X-Requested-With, Content-Type, Accept',
'access-control-allow-credentials': 'true',
'access-control-allow-methods': 'GET, POST, OPTIONS, PUT, DELETE, PATCH',
'set-cookie': [
'tkAccess=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjgyYWQ1NzRhLWRiNTktNGI0Ni1hZTI3LTE5NjZmZmNiNTY5NSIsInVzZXJuYW1lIjoiRmVsZHVxdWUiLCJlbWFpbCI6ImpmLmR1cXVlNTU3QGdtYWlsLmNvbSIsImF2YXRhcl91cmwiOm51bGwsImlhdCI6MTc0MTY2MjE3NiwiZXhwIjoxNzQxNjYzMDc2fQ.oUGMMIXkc4fHyT3P1dCSNhJUSA_l-auAYNSetKo5sDc; Max-Age=900; Path=/; Expires=Tue, 11 Mar 2025 03:17:56
GMT; HttpOnly'
],
'content-type': 'application/json; charset=utf-8',
'content-length': '326',
etag: 'W/"146-rIF2qKmlMH9Anfi3rTofaVHuYhw"',
date: 'Tue, 11 Mar 2025 03:02:56 GMT',
connection: 'keep-alive',
'keep-alive': 'timeout=5'
}
Hmmmmm, okay so Axios ive never used. Where in the code you provided is where your setting the cookie? I dont see it.
@Jboncz Hmmmmm, okay so Axios ive never used. Where in the code you provided is where your setting the cookie? I dont see it.
When adding the res.cookie the token is supposed to add itself, yet I created this function using a nextjs function but it still never sets the cookie.
export async function updateAccessToken(token: string) {
(await cookies()).set("tkAccess", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
maxAge: 60 * 15,
});
}
The problem really is. Every time I make a request on the server side and it needs to update the token it never updates it.
I also tried to use the nextjs route handler but it doesn't work either. (The request is made from the axios interceptor.)
Can you show me where your calling updateAccessToken?
The file you provided really doesnt tell me much
Im about to head to bed, ill check in on this tomorrow and spend a little more time going through the axios documentation. Sorry getting late.
I used it in a route handler and also tested it in the interceptor (No error allowed).
This appears when I try to use it in the interceptor.
I have tried too many ways and no solution so far.
Thats right. okay one sec lemme give you something to try.
@Jboncz Im about to head to bed, ill check in on this tomorrow and spend a little more time going through the axios documentation. Sorry getting late.
No problem anyway thank you very much for taking the time to help me.
The interceptor is running on the server side right? Like I said never used axios so not familiar
@Jboncz The interceptor is running on the server side right? Like I said never used axios so not familiar
It depends on where you are making the request from, whether from the client or server, that's why I created two instances
const clientApi = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
timeout: 10000,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
withCredentials: true, // This only works on the client side
});
// Create a server-side Axios instance
const serverApi = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL || process.env.API_URL, // Fallback to server env
timeout: 10000,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
withCredentials: true, // This only works on the client side
});
Gotcha, if your purely on the client, you cant set the cookies
@Jboncz Gotcha, if your purely on the client, you cant set the cookies
From the client there is no major difficulty, the problem is always on the server.
ok one sec
'use client';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useState } from "react";
import { setCookie } from "./actions";
export default function Page() {
const [value, setValue] = useState('')
return (
<div >
<Input value={value} onChange={(v) => { setValue(v.target.value) }} />
<Button onClick={async () => await setCookie('boo', value)}>Click me to set cookie!</Button>
</div>
);
}
"use server"
import { cookies } from "next/headers"
export async function setCookie(name, value) {
const cookieStore = await cookies()
cookieStore.set(name, value, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
maxAge: 60 * 60 * 24 * 7, // 1 week
path: "/",
})
return;
}
This is obviously super crude but heres an example
You will see that whatever value you put in the box is what the cookie will have
thats from the server side.
@CodigoK 401
export async function updateAccessToken(token: string) {
(await cookies()).set("tkAccess", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
maxAge: 60 * 15,
});
}
addding 'use server' to the top of this may correct your issue
yeah just remove the async
yes hahahhaha sorry
xD
all good bud
xD
Does that at least point you in the right direction?
Hopefully
works
So now we are able to set the cookie from the server side without issue. Next move onto trying to hit that updateAccessToken
method
Its essentially the same thing, it should work.
Idk if this is suppose to be how your doing this with Axios, because I dont know axios so its hard for me to understand whats going on with the interceptor and stuff.
@CodigoK 401 This appears when I try to use it in the interceptor.
Okay so now try it in whatever flow you were trying earlier when you were gettting
xD
how does the interceptor get called? In middleware?
Okay forreal I gota go to bed, ill look more tomorrow.
is an axe interceptor, it has 2 axes, one for the request and one for the response.
The use I am giving it is that every time it makes a request and fails by 401 it goes and refreshes the token and the idea is to set the cookie for next requests and make the current request again.
The use I am giving it is that every time it makes a request and fails by 401 it goes and refreshes the token and the idea is to set the cookie for next requests and make the current request again.
It could also be that axios does not work well so the best idea is to use fetch.
is the third window the code for the
get()
method you're calling in your service?Anyway, you're trying to set cookies from within the context of the server, in your server component and that doesn't work. You can't
https://discordapp.com/channels/752553802359505017/1322470128549498971/1322473633892925511
set()
cookies (or equivalent) in Server Components [(see docs)](https://nextjs.org/docs/app/api-reference/functions/cookies#understanding-cookie-behavior-in-server-components), you can only read them. In order to write to cookies, you need to be in Server Actions or Route Handlers, and call them from the client.https://discordapp.com/channels/752553802359505017/1322470128549498971/1322473633892925511
Oh yeah heβs right. If you turned roomlist into a client component it would run the server action fine.