I have laravel as backend and next.js as frontend of my website. I use laravel sanctum for authentication.
My laravel app and next.js app are in the same host, then I can use session-base sanctum for authentication without use token.
After login there is no problem when I want to access the routes that are protected with middleware aute:sanctum in client side of next.js but in the server side always get error unauthenticated.
This is my axios config and my function for fetch data in next.js:
// axios instance
const axiosInstance = axios.create({
baseURL: 'localhost:8000',
withCredentials: true,
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
});
const onRequest = (config) => {
if ((
config.method == 'post' ||
config.method == 'put' ||
config.method == 'delete'
/* other methods you want to add here */
) &&
!Cookies.get('XSRF-TOKEN')) {
return setCSRFToken()
.then(response => config);
}
return config;
}
const setCSRFToken = () => {
return axiosInstance.get('api/v1/csrf-cookie');
}
// attach your interceptor
axiosInstance.interceptors.request.use(onRequest, null);
// fetch data:
export async function getServerSideProps(context) {
const { query, req } = context;
const {
page,
search_term,
nip,
tableName
} = query;
try {
const response = await ax.post(`api/v1/admin/${tableName}`, { page: page, search_term: search_term, nip: nip || 10 }, {
withCredentials: true,
headers: {
Cookie: req.headers.cookie,
}
});
return {
props: {
initItems: response.data.data,
initMeta: response.data.meta,
initSearchTerm: search_term || '',
iniNip: nip || 10
}
}
} catch (err) {
console.log(err);
return {
notFound: true,
}
}
}