When using Express, I used to store users like request.user
:
import jwt from "jsonwebtoken"; import asyncHandler from "express-async-handler"; import User from "../models/userModel.js"; const protect = asyncHandler(async (req, res, next) => { let token; token = req.cookies.jwt; if (token) { try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = await User.findById(decoded.userId).select("-password"); next(); } catch (error) { res.status(401); throw new Error("Not authorized , invalid token"); } } else { res.status(401); throw new Error("Not authorized , no token"); } }); export { protect }; And I was able to get the current user like this : const createPost = asyncHandler(async (req, res) => { const { content, image } = req.body; const user = req.user;
But how to do this using NextJS 13 API routing and middleware and how to use cookies. New to NextJS so any help would be greatly appreciated.
In Next.js, you can use the cookie extensions on NextRequest and NextResponse to read and manipulate cookies. The specific method is as follows:
First, you need to import cookies from next/headers:
Then, you can get a cookie like this:
To set a cookie, you need to return a new response using the Set-Cookie header:
You can also use the NextRequest object to read cookies:
For incoming requests, cookies have the following methods: get, getAll, set and delete cookies. You can use has to check if a cookie exists, or clear to delete all cookies.
For outgoing responses, the cookie has the following methods get, getAll, set and delete.
Here are examples of how to use these methods: