Cookies are not Available in Middleware
Unanswered
Northeast Congo Lion posted this in #help-forum
Northeast Congo LionOP
// middleware.js
import { NextResponse, NextRequest } from "next/server";
import { cookies } from "next/headers";
export async function middleware(request) {
const url = `${process.env.NEXT_PUBLIC_BACKLINK}/dashboard/auth`;
console.log(request.cookies.getAll()); //returns []
try {
const res = await fetch(url, {
credentials: 'include',
});
if (res.ok) {
// Continue to the next middleware
return NextResponse.next();
} else {
console.log('Authentication failed:');
// Redirect to login if authentication fails
// return NextResponse.redirect(new URL('/login', request.nextUrl));
}
} catch (error) {
// Handle fetch errors
console.error("Fetch error:", error);
// You may want to redirect to an error page or handle the error differently
return NextResponse.error(new Error("Internal Server Error"));
}
}
export const config = {
matcher: ["/dashboard/:path*"],
};Cookies are missing here. I have tried everything but this NextJS middleware does not worked.
Perfectly working on localhost.
Other routes are sending cookies as well.
6 Replies
@Ray try this
ts
const res = await fetch(url, {
headers: new Headers(request.headers)
});
Northeast Congo LionOP
Already tried. then Cookies is null
@Northeast Congo Lion Already tried. then Cookies is null
check the cookies in the browser dev tools and make sure
NEXT_PUBLIC_BACKLINK is in the domain column@Ray check the cookies in the browser dev tools and make sure `NEXT_PUBLIC_BACKLINK` is in the domain column
Northeast Congo LionOP
Yes. As i mentioned before, same request is working on my other other client-side pages.
Basically if i can access cookies (and token from there) from middleware, i have other workaround to send token with request.
@Ray try this
ts
const res = await fetch(url, {
headers: new Headers(request.headers)
});
Northeast Congo LionOP
Update now getting 404 error as response. Before it was 401