I created a middleware using NextJS 15. I am able to decode the token successfully and got userId and username and i want to attach it with req body object. once the todo is created by a user it should add the userId and username as well inside the a todo
For example:
{
"message": "A New Todo created successfully",
"newTodo": {
"title": "Learn Sundarkand",
"status": false,
"date": "2025-01-20T06:58:20.469Z",
"_id": "678df40c9668b2d9b71c8f99",
"userId" : "678df40c9668b2d9b71c8",
"userName" : "xyz",
"__v": 0
}
}
this is my middlware code snippet
export async function middleware(req) {
console.log("------>Middleware triggered");
try {
const token = await getCookies("jwtToken");
if (!token) {
return NextResponse.json(
{ message: "Unauthorized Access" },
{ status: 401 }
).redirect(new URL("/login", request.url)); // --- what should i add in request.url ? Find out here
}
// verify token using jose
const {
payload: { userId, username },
} = await jwtVerify(
token,
new TextEncoder().encode(process.env.JWT_SECRET)
);
console.log("Decoded Token:", username, userId);
// console.log("Request", request);
// attach with the request object ---- > TEST this on tomorrow.
const body = await req.json();
body.userId = userId;
body.username = username;
console.log("REq---->", body);
return NextResponse.json({ body }).next();
} catch (error) {
return NextResponse.json({ message: error.message }, { status: 500 });
}
}
// See "Matching Paths" below to learn more
export const config = {
matcher: ["/todos/create"],
};