I'm developing an app with docker, nginx, laravel and nextjs.
Next is running in localhost:3000 and nginx in localhost:9000, and I have the problem when a form is sent, the token is not added automatically in axios and this is for the domain but I don't know how to solve. I'm using sanctum and I can see the token in the browser.
Axios in next:
import axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
import { getCookie } from '@/utils/cookies/cookies';
import { DEFAULT_LOCALE } from '@/langs/locales';
import { APP_LANGUAGE } from '@/utils/cookies/constants';
function isServer(): boolean {
return typeof window === 'undefined';
}
function createHttpClient(baseURL: string): AxiosInstance {
return axios.create({
baseURL,
withCredentials: true,
headers: {
'Content-type': 'application/json',
Accept: 'application/json',
Timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
},
});
}
function setAppLanguageHeader(
config: InternalAxiosRequestConfig
): InternalAxiosRequestConfig {
if (config && config.headers) {
if (!isServer()) {
config.headers[APP_LANGUAGE] = getCookie('NEXT_LOCALE') ?? DEFAULT_LOCALE;
}
}
return config;
}
const clientAPIURL = createHttpClient(process.env.NEXT_PUBLIC_CLIENT_API_URL);
const serverAPIURL = createHttpClient(process.env.NEXT_PUBLIC_SERVER_API_URL);
clientAPIURL.interceptors.request.use(setAppLanguageHeader);
serverAPIURL.interceptors.request.use(setAppLanguageHeader);
export { clientAPIURL, serverAPIURL };
Axios .env:
NEXT_PUBLIC_CLIENT_API_URL=http://localhost:9000/api
and in both, laravel and next I have the cors and withCredentials true.
NGINX config:
server {
listen 80;
listen [::]:80;
server_name localhost;
root /var/www/finaldraw/nadal/public;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
charset utf-8;
if (!-d $request_filename){
rewrite ^/(.+)/$ /$1 permanent;
}
## Handle Horizon requests
location /findra-queues/horizon {
try_files $uri $uri/ /index.php?$query_string;
# PHP-FPM configuration
include fastcgi_params;
fastcgi_pass findra-php:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_hide_header X-Powered-By;
}
## Handle PHP requests
location ~ [^/]\.php(/|$) {
# Mitigate / vulnerabilities
fastcgi_param HTTP_PROXY "";
include fastcgi_params;
fastcgi_pass findra-php:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_hide_header X-Powered-By;
}
## Handle API requests and pass them to index.php if the file doesn't exist
location /{
add_header Access-Control-Allow-Origin localhost;
try_files $uri $uri/ /index.php?$query_string;
}
# deny access to .htaccess files, if Apache's document root concurs with nginx's one
location ~ /\.ht {
deny all;
}
}