Not receiving Cookies in middleware in Production
Answered
Rex posted this in #help-forum
RexOP
I working on a wbe app and it works fine on the local environment but when I deployed on Vercel I am not receiving cookies in the middleware. Why is that? I Based on the cookies I will be redirecting user to the different route
middleware.js
In my local environment I get the following
Log on the vercel
middleware.js
import { NextResponse } from "next/server";
export async function middleware(req) {
console.log("request: ", req);
console.log("req: ", req.cookies.get("next-auth.session-token"));
let token;
if (req.cookies.get("next-auth.session-token")) {
token = req.cookies.get("next-auth.csrf-token").value;
}
console.log("NEXT URL: ", req.nextUrl);
const path = req.nextUrl.pathname;
const isPublicPath = path === "/signin" || path === "/register";
if (isPublicPath && token) {
return NextResponse.redirect(new URL("/", req.nextUrl));
}
if (!isPublicPath && !token) {
console.log("redirectinh to the signin page............");
return NextResponse.redirect(new URL("/signin", req.nextUrl));
}
}
export const config = {
matcher: ["/register", "/signin", "/", "/events", "/register/:path*"],
};In my local environment I get the following
request: {
cookies: RequestCookies {"next-auth.csrf-token":{"name":"next-auth.csrf-token","value":"cf1bb1fce63cd50055d9abb1d837fd2634cc837c3be60703b6f42ec568f17f62|23c79fa61f6fbe37dc1f27d8f64b5cf321dad580b587140a1e3f6196546506b1"},"next-auth.callback-url":{"name":"next-auth.callback-url","value":"http://localhost:3000/register"},"next-auth.session-token":{"name":"next-auth.session-token","value":"eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..CGbW-u7LZ3Dfb8sK.2buJI7ykActkXti_A8X0d0mDOYimncljaPuL8GGLjCc9a69XzxjXDZF3TyARkgsiJYaiykeXgLc6OdaC-LS1ZuZednZWtG0vbM_nn6AhuC2LPjXAy2t6IMN5CeB0CX9q9O28UiAJYBzcoCwkyIqbWIlpiy65ZdIaX4uTzEV1EALLfP00yZ1D5d9vn7lFoTbW0Zohjj1m6W-Y5jPpXEEdop2t3qFHAfZsGZln--Hvvg.qdtVOnHTGsv97BfMFEuA8A"}},
// ...stuff
}Log on the vercel
request: {
cookies: RequestCookies {},
geo: {// data}
// rest of data here
} Answered by Rex
Solved it
I am using
I am using
const token = await getToken({ req }); to check whether the user is authenticated or not instead of cookies2 Replies
RexOP
After registering I am signing the user like this using the next auth
const onSubmit = async (data) => {
setLoading(true);
try {
const response = await axios.post("/api/register", data);
console.log("response:", response.data);
const { email, password } = data;
const result = await signIn("credentials", {
email,
password,
redirect: false,
});
setUser(response.data);
router.push("/register/profile");
} catch (error) {
if (error) {
setEmailError("email already in use");
}
}
setLoading(false);
};RexOP
Solved it
I am using
I am using
const token = await getToken({ req }); to check whether the user is authenticated or not instead of cookiesAnswer