Nextjs axios request to sanctum api works on frontend but not on the backend {middleware and api routes} #110201
Replies: 1 comment 1 reply
|
The difference is where each request actually runs. useEffect executes in the browser, so the browser automatically attaches your session/XSRF cookies to the axios call (that's why it returns 200). Next.js middleware runs server-side (Edge/Node runtime) — it's essentially a separate HTTP client with no access to the browser's cookie jar, so axios sends the request with no cookies at all unless you forward them explicitly. Fix: read the cookies off the incoming request and attach them manually to the outgoing call: import { NextResponse } from 'next/server'; export async function middleware(request) { try { |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Body
Hi,




Context: I am working on this basic authentication system using Nextjs and laravel sanctum, I have the user registration setup correctly and I can register and logout everything works fine except when I make a request in the middleware to the /api/user endpoint to retrieve the user, then I get error 401 Unauthorized even when I have logged in on the frontend, the weird thing is that the same request works when I make it inside a useEffect in the frontend and returms 200 ok with the user info in the response. my frontend is hosted on localhost:3000 whilst my backend is on localhost:8000
env sanctum config:
sanctum api routes:
nextjs frontend (this returns ok 200 response with user info):
nextjs api route (this returns 401 Unauthorized):
objective: to make an http request to sanctum api to see if user is authenticated or not then send him either to the dashboard or login page (this must be done either inside the middleware or the backend) I appreciate any help I could get to solve this issue
Guidelines
All reactions