Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

650
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda