How do I set the JWT provided by strapi as HTTP-ONLY?

System Information
  • Strapi Version:
  • Operating System:
  • Database:
  • Node Version:
  • NPM Version:
  • Yarn Version:

I just learned that if the jwt is stored in a cookie and is set to httpOnly then when I use fetch , I dont need to sent jwt. The cookie gets send automatically if I put “credentials” attribute in the header. Is this true ? If yes then how do I put those jwt in a httpOnly cookie?

Pardon If my explanation confuses you. I’m already bit lost in this subject and English is not my 1st language.

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.

I also found success in backend side by creating a file under User & Permissions plugin and I customized it on backend rather than of frontend side API but when I send a request to backend to fetch data the cookies aren’t extracted from cookies section and can’t store jwt from it. We should collab to figure it out.
what do you say ?

can you please show any example for strapi v4? i can’t extend users permissions