I have a Next.js application where I am trying to set up Axios to include the CSRF token automatically in all non-GET requests. I have written the following code to retrieve the XSRF-TOKEN from cookies and set it in the request headers. However, I’m facing issues with retrieving.I am Calling api that set Cookies in my browser
Here is my code:
function getCookie(name) { const cookie = document.cookie
.split("; ")
.find((item) => item.startsWith(`${name}=`)); console.log(document.cookie); // Debug: check what cookies are present if (!cookie) return null;
return decodeURIComponent(cookie.split("=")[1]); // Fixed: Correctly split the cookie value }
const axios = Axios.create({ baseURL: process.env.NEXT_PUBLIC_BACKEND_URL, headers: {
"Content-Type": "application/json", }, withCredentials: true, withXSRFToken: true, });
axios.interceptors.request.use(async (req) => { if (req.method === "get") return req;
let csrfToken = getCookie("XSRF-TOKEN"); if (!csrfToken) {
await axios.get("/sanctum/csrf-cookie");
csrfToken = getCookie("XSRF-TOKEN"); } req.headers["X-XSRF-TOKEN"] = csrfToken; return req; });
export default axios;
Issues:
Retrieving the Cookie: The getCookie function does not always retrieve the XSRF-TOKEN correctly.
Setting the Cookie: Even after successfully calling /sanctum/csrf-cookie, the XSRF-TOKEN is sometimes still not present.
What I’ve Tried:
Debugging document.cookie: Added a console log to check the cookies present in the document.
Manual Request to /sanctum/csrf-cookie: Tried manually hitting the endpoint to ensure the CSRF cookie is being set.
Questions:
Is there a better way to retrieve cookies in a Next.js application?
Are there specific browser settings or CORS configurations that might be interfering with cookie handling?
How can I ensure that the CSRF token is reliably set and retrieved across different environments and browsers?
I am attaching Image of Cookies Present in Headers