How to pass JWT token from Header Set-Cookie to Headers Authorization: Bearer token

So after doing some research I found what to do for this.
So basically, I setup-ed a middleware whose work was to get the jwt token from header cookies and set Authorization: Bearer token

Answer

Create custom middleware

./src/middlewares/TokenPlacer.js
(Filename can be of your choice)

module.exports = () => {
  return async (ctx, next) => {
    const cookies = ctx.request.header.cookie || false;
    if (cookies) {
      let token = cookies
        .split(";")
        .find((c) => c.trim().startsWith("jwt="))
        .split("=")[1];
      if (token) {
        ctx.request.header.authorization = `Bearer ${token}`;
      }
    }
    await next();
  };
};

Here I have saved my JWT token as jwt in the cookie so change it accordingly!

Load the custom middleware

Then locate the middleware file in ./config/middleware.js
If you haven’t used any middleware or customized anything then it should look like this

module.exports = [
  "strapi::errors",
  "strapi::security",
  "strapi::cors",
  "strapi::poweredBy",
  "strapi::logger",
  "strapi::query",
  "strapi::body",
  "strapi::session",
  "strapi::favicon",
  "strapi::public",
];

Now here we need to tell the Strapi to load our custom middleware
So just add "global::__YOUR__MIDDLEWARE_FILENAME__", at the end, so for me it "global::TokenPlacer", , so it would look like this now

module.exports = [
  "strapi::errors",
  "strapi::security",
  "strapi::cors",
  "strapi::poweredBy",
  "strapi::logger",
  "strapi::query",
  "strapi::body",
  "strapi::session",
  "strapi::favicon",
  "strapi::public",
  "global::TokenPlacer",
];

Learn more about Strapi Middleware and customize accordingly - Official Strapi Docs v4

2 Likes