Amir Hossein
Amir Hossein

Reputation: 1144

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

Upvotes: 0

Views: 3058

Answers (2)

Amir Hossein
Amir Hossein

Reputation: 1144

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(() => {
        //
      });

Upvotes: 0

Ivan V.
Ivan V.

Reputation: 8101

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.

Upvotes: 0

Related Questions