I’m by no means an expert, but I’ve implemented this successfully using Strapi as my backend and Next.js as my frontend.
- In Next.js I created an API route that gets called when you log in (e.g. /api/login)
- You send a post request with your credentials to that route
- Next.js then sends a post request to Strapi’s login API, passing on the credentials
- Next.js receives the JWT from Strapi and then sets the cookie server-side (because httpOnly cookies can only be set by the server)
// Next.js --- /api/login.js
export default async (req, res)=> {
const {identifier, password} = req.body;
await strapiAxios().post("/api/auth/local", {
identifier, password
}).then(async (response)=> {
res.setHeader(
"Set-Cookie", [
cookie.serialize("JWT", response.data.jwt, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
maxAge: 60 * 60 * 24 * 365, // cookie expires after 1 year. However, NEVER store JWT's for this long
sameSite: "strict",
path: "/",
})
])
return res.status(200).json({success: "Logged in", user: response.data.user});
}).catch((error)=> {
// handle errors
})
}
Using httpOnly cookies should be a requirement when storing JWT’s, as it’s more secure.
Note that the above code is just a stripped down and generalized version of my actual implementation and I haven’t tested it on functionality.