Maybe I’m approaching this the wrong way. I have built an API on expressjs with this auth middleware:
const { verifyToken } = require("../controllers/utils/jwt");
exports.requireAuth = (req, res, next) => {
try {
const token = req.cookies.jwt;
if (!token) return res.status(403).json({ error: "No token provided" });
verifyToken(token, (error, decoded) => {
if (error) {
return res.status(403).json({ error: error.message });
}
req.userId = decoded;
next();
});
} catch (error) {
return res.status(500).json({ error: error.message });
}
};
verifyToken
just runs jwt.verify(token, JWT_SECRET, cb)
.
So I’m trying to use a middleware in Nextjs to verify that the user is logged in (and the jwt has not been tampered with). This is my Nextjs middleware:
async function getUser() {
try {
const res = await fetch(`${API_URL}/users/me`, {
method: "GET",
credentials: "include",
});
const data = await res.json();
return data;
} catch (e) {
console.log(e);
}
}
export async function middleware(request: NextRequest) {
const user = await getUser();
if (user.error) {
const url = request.nextUrl.clone();
url.pathname = "/";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/profile"],
};
My impression is that setting credentials to include
should be enough since it has worked on other parts of the code. However it doesn’t seem to work here since the response is always “No token provided” even if I see the token in the Cookies section of the dev tools.
I’ve tried adding the credentials field to the fetch options. I’ve tried logging both ends of the code but I can’t seem to land where the problem is.