1

I have hosted my Laravel application in a Namecheap hosting running Litespeed Server with a domain at -> api.example.com

My Next.js SPA frontend is being run from a digital ocean droplet with nginx reverse proxy with the domain -> test.example.com.

I have used Sanctum in Laravel to authenticate the SPA. The sanctum/csrf-cookie endpoint works and sets an XSRF-COOKIE. Next the api/login endpoint also works for me. It authenticates the user and is sending expected response. Retrying the api/login says 'Already Authenticated' and does not login again But following that when I try to fetch the user using api/user endpoints I get 401 Unauthenticated Status and response.

the .env file in Laravel includes ---

APP_URL=https://api.example.com
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
COOKIE_SAME_SITE_POLICY=strict
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=*.example.com
SANCTUM_STATEFUL_DOMAINS=https://test.example.com
SESSION_SECURE_COOKIE=false
SPA_URL=https://test.example.com

I am using Axios in the frontend. The global axios instance looks like ---

import Axios from 'axios'

const axios = Axios.create({
    baseURL: process.env.NEXT_PUBLIC_BACKEND_URL,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Access-Control-Allow-Origin': process.env.NEXT_PUBLIC_BACKEND_URL,
        'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
    },
    withCredentials: true,
})

export default axios

The .env.local file in the frontend has these ---

SERVER=api.example.com
APP=test.example.com
NEXT_PUBLIC_BACKEND_URL=https://$SERVER
NEXT_PUBLIC_APP_URL=https://$APP

I have some non sanctum routes in my backend, laravel website. These are public unprotected routes and they properly respond without any fuss. However, I believe I am missing out on any cors configuration in laravel or in my frontend that is keeping me away from my desired output.

Please note example.com is not my actual tld.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Joy Ram Sen Gupta
  • 365
  • 1
  • 6
  • 16
  • COOKIE_SAME_SITE_POLICY=strict This mean cookie will be sended only to the site A, beeginning backend in site B, site B will not see cookies sotred by site A – Stefano Martini Jan 12 '23 at 10:30

0 Answers0