Search code examples
javascriptstrapi

Strapi v4: middleware from plugin


I have created plugin, for example TagsPlugin. The main idea that plugin for example add Tags for any content-type. I need create middleware to add Tags to each request if they are exists for current content-type

I create Middleware in my-plugin-folder/server/middlewares/tags.ts what looks like

/**
 * `tags` middleware
 */

import { Strapi } from '@strapi/strapi';

const tags = (config, { strapi }: { strapi: Strapi }) => {
  // Add your own logic here.
  return async (ctx, next) => {
    strapi.log.info('In tags middleware.');
    console.log('TAGS MIDDLEWARE');

    await next();
  };
};

export default tags;

And in my-plugin-folder/server/register.ts depending on documentation i've add strapi.server.use(middlewares.tags); - in this case all app don't work without any error. I need to add this middleware globally, but i cant find info how to do that. alsoo i tried add strapi.middleware('plugin::plugin-name.middleware-name'); to /my-app/config/middleares.ts` but its also get me an error.

What the correct way to add global middleware from plugin instead creating app-level middleware?


Solution

  • You can refer this document: https://docs.strapi.io/dev-docs/api/plugins/server-api#middlewares

    plugin-folder/server/middlewares/tags.ts

    'use strict';
    const tags = async (ctx, next) => {
      strapi.log.info(`tags: ${ctx.method} ${ctx.originalUrl} ${ctx.status} - ${ctx.headers['host']}`);
    
      await next();
    };
    export default tags;
    

    => the export parameters of plugin middleware is different to application's middleware

    plugin-folder/server/register.ts

    import {Strapi} from '@strapi/strapi';
    
    import tagsMiddleware from './middlewares/tags';
    
    export default ({strapi}: {strapi: Strapi}) => {
      // register phase
      strapi.server.use(tagsMiddleware);
      // or
      /*
      strapi.server.use(async (ctx: any, next: any) => {
        strapi.log.info(`tags: ${ctx.method} ${ctx.originalUrl} ${ctx.status} - ${ctx.headers['host']}`);
    
        await next();
      });
      */
    };