Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

653
Vistas
cannot get XSRF-TOKEN from cookie in nextjs (Reactjs)

I create a login form using Nextjs and backend with Laravel 8, I generate an XSRF-TOKEN in Laravel then set it on cookie, I can see the token inside inspect element> application tab> cookie section, but I can't set it on my fetch request to make my login, I using redux to store my data such: products, auth, cart and etc

AuthAction.js code:

export const LOGIN_AUTH = "LOGIN_AUTH";
export const LOGOUT_AUTH = "LOGOUT_AUTH";

export const HandleLogin = (data) => {
  return async (dispatch, getState) => {
    const getCsrf = await fetch("http://localhost:8000/sanctum/csrf-cookie");

    if (!getCsrf.ok) {
      throw new Error("Faild to set csrf token");
    }

    console.log("getCsrf", cookie.load("XSRF-TOKEN"));

    const response = await fetch("http://localhost:8000/api/app/user/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw Error("Login faild");
    }

    try {
      const responseData = await response.json();

      console.log("login", responseData);

      dispatch({
        type: LOGIN_AUTH,
        user: responseData,
      });
    } catch (err) {
      console.log("Login err", err);
      throw err;
    }
  };
};

after console.log("getCsrf", cookie.load("XSRF-TOKEN")); nothing happened. what do I do wrong in my code?

cookie screenshot:

enter image description here

request response: enter image description here

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Since your next.js and laravel apps are on different origins, you need to set fetch to explicitly send cookies.

   const response = await fetch("http://localhost:8000/api/app/user/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
      credentials: 'include'
    });

You can read more about the credentials property in the MDN docs

Also, you can read the cookie in the front-end if it's http-only cookie.

Also, don't forget to set up Cross origin resource sharing in your backend app.

about 4 years ago · Santiago Trujillo Denunciar

0

Use axios instead of fetch.

Example:

axios
      .get("http://localhost:8000/sanctum/csrf-cookie", {
        withCredentials: true,
      })
      .then((response) => {
        axios("http://localhost:8000/api/app/user/login", {
          method: "post",
          data: data,
          withCredentials: true,
        })
          .then((response) => {
            console.log("login", response.data);
          })
          .catch((error) => {
            console.log(error);
          });
      })
      .catch((error) => {
        // handle error
        console.log(error);
      })
      .then(() => {
        //
      });
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda