0

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

3
  • if (!getCsrf.ok) - console.log here. What does it give to you? Commented Apr 11, 2022 at 7:54
  • it's not throwing an error, the response code is 204 and it's true, the request is success I can see the cookie in the application tab but I can't access it to use in my post request Commented Apr 11, 2022 at 8:02
  • I added 2 screen shot of my resualts Commented Apr 11, 2022 at 8:33

2 Answers 2

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.

4
  • I do that and i get this errors: Access to fetch at 'http://localhost:8000/api/app/user/login' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. POST http://localhost:8000/api/app/user/login net::ERR_FAILED 419 Commented Apr 11, 2022 at 8:57
  • You need to setup Cross origin resource sharing in your backend app.
    – Ivan V.
    Commented Apr 11, 2022 at 10:09
  • I already set my cors origins in my app Commented Apr 12, 2022 at 3:51
  • I need a CSRF token for posting data, I create it in my backend and set it in a cookie but I don't have access that cookie from my front end app Commented Apr 12, 2022 at 3:53
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(() => {
        //
      });
1
  • You asked for a solution using fetch. This only says to use a different method/ package for the http request instead of explaining how to do it with fetch. Commented Oct 4, 2023 at 18:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.