Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uminnkhantnaing's avatar

Can't log in to Laravel API on staging server (Laravel Forge) via NextJs or Postman

I have developed an API project on Laravel with Sanctum (Token) and NextJs for the frontend. I have setup things up correctly and everything is working fine on Localhost.

I deployed the project on Laravel Forge with one custom subdomain (eg. api.example.com). I run php artisan storage:link and php artisan migrate:fresh --seed (with env as staging) as per their guide (cd /to the path && artisan command) and this works. FRONTEND_URL in env has also been updated to the live frontend url (eg. nextjs.example.com).

I tried logging in to the backend from nextjs after deploying Backend on Laravel Forge and NextJs on Vercel. https://api.example.com/sanctum/csrf-cookie is working correctly as it responds to the browser with the XSRF-TOKEN. But it fails on login with csrf-token mismatch.

In the chrome's devtools, laravel session and xsrf token are not found on Application/Cookies/domain. In network tab, /sanctum/csrf-cookie is successful with status - 204 and /login is failed with status - 429.

Then I tried logging into it with Postman and the same thing happens. I can request the csrf-cookie separately but can not log in to the api backend with responded token. However, it is working fine on the localhost.

This is a piece of my working codes on localhost (NextJs)

const csrf = () => axios.get('/sanctum/csrf-cookie');

const login = async (loginDetails, setErrors) => {
    setErrors('');

    await csrf();

    await axios
      .post('/login', loginDetails, {
        headers: {
          'X-XSRF-TOKEN': getCookie('XSRF-TOKEN'),
        },
      })
      .then(async (res) => {
        if (res.data.status === 401) {
          setErrors(res.data.message);
        } else {
          localStorage.setItem('user_token', res.data.data.token);
          setCookie('user_token', res.data.data.token);

          await axios
            .get('/api/authenticated-user', {
              headers: {
                Authorization: `Bearer ${localStorage.getItem('user_token')}`,
              },
            })
            .then((res) => {
              localStorage.setItem(
                'user_data',
                JSON.stringify(res.data.data)
              );
            });

          router.push('/dashboard/);
        }
      })
      .catch((err) => {
        setErrors(err.response.data.message);
      });
  };
0 likes
0 replies

Please or to participate in this conversation.