I have a NextJS Frontend with Next-Auth installed and a Laravel Backend using Sanctum When I try to login using the signIn function of Next-Auth, it gives me this error:
Request failed with status code 419
419 has to do with CSRF token but I am setting the token by calling the sanctum/csrf-cookie route before calling the login method
[...nextauth.js]
CredentialsProvider
({
name: 'Email and Password',
credentials: {
email: {label: "Email", type: "email", placeholder: "Your Email"},
password: {label: "Password", type: "Password"}
},
async authorize({email, password}, req) {
await apiClient.get("/sanctum/csrf-cookie");
const user = await apiClient.post('/customer/login', {
email: email,
password: password,
});
if (user) {
return user
} else {
return null
}
}
})
apiClient.js
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'http://localhost:8000',
withCredentials: true,
});
export default apiClient;
The first time I try to sign in, I get redirected to /api/auth/signIn?csrf=true
and when I try to sign in again I'm redirected to /api/auth/error?error=Request failed with status code 419
I tried accessing the backend login routes using an API call from the client and it worked without any hitches.
Why is it failing for a request between two servers while it works fine when called from the client? I am not entirely grasping why the Next server isn't able to send a request with the csrf header to the Laravel Server. Is the cookie not set by the first call to sanctum/csrf-cookie when it comes to the server? Does CSRF not apply when talking between two server?
What am I missing here? Any help would be appreciated.
Following a comment, I tried explicitly passing passing the cookies following this question - Why are cookies not sent to the server via getServerSideProps in Next.js? but I still get a CSRF token mismatch error.
getServerSideProps
but the same applies to API routes, they both run on the server. – Ireland