DEV Community

IHesamI
IHesamI

Posted on

Strapi Tips #1: Adding Custom JWT Protection to Your API

Hello!
This is the first post in a series where I’ll share my experiences and current knowledge about Strapi.

In this post, we’ll create a custom middleware to authenticate JWT tokens in your Strapi project.

Creating a JWT Authentication Middleware
Let’s start by creating a new middleware file named:
src/middlewares/jwt-authentication.ts

Now, add the following code:

import jwt from 'jsonwebtoken';
import { Context } from 'koa';

export default (config, { strapi }) => {
  return async (ctx: Context, next) => {
    try {
      const token = ctx.req.headers.authorization?.split(' ')[1];
      const tokenInfo = jwt.verify(token, process.env.YOUR_JWT_SECRET);
      ctx.state.user = tokenInfo;
      await next();
    } catch (err) {
      console.error(err);
      return ctx.unauthorized();
    }
  };
};
Enter fullscreen mode Exit fullscreen mode

This middleware does the following:

Extracts the JWT token from the Authorization header.

Verifies and decodes the token using the secret key.

Attaches the user info to ctx.state.user if the token is valid.

Calls ctx.unauthorized() if the token is missing or invalid.

Make sure to store your JWT secret in an environment variable called YOUR_JWT_SECRET.

Using the Middleware in a Custom Route
To protect a route using this middleware, define it like this:

{
  method: 'GET',
  path: '/your_protected_route',
  handler: 'your_controller',
  config: {
    middlewares: ['global::jwt-authentication'],
  },
}

Enter fullscreen mode Exit fullscreen mode

You now have a working JWT authentication middleware to protect your custom API routes.

Thanks for reading — stay tuned for more Strapi tips in upcoming posts!

Top comments (0)