How to dynamically inject policies to routes?

While searching I eventually ended up at this comment `ctx.state` is empty before `await next()` in last-registered global middleware · Issue #19529 · strapi/strapi · GitHub but I don’t know how I can do it. I checked the strapi object that gets passed to the middleware factory, but it doesn’t seem to have a routes property or at least I don’t know where to look.

Could you please help provide an example on how to dynamically inject a global policy to all routes?

This topic has been created from a Discord post (1254824007715389573) to give it more visibility.
It will be on Read-Only mode here.
Join the conversation on Discord

You can generate and configure Route Policies in the same way as you do with Route Middlewares.

Here is a good article explaning things well, Understanding the Strapi Request Flow: A Journey from KOA to Modern Middleware Architecture.

And here is an example to get you going:


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

  // Register your custom middleware to inject the global policy
  {
    name: 'global::injectGlobalPolicy',
    config: {
      // Middleware configuration goes here if needed
    },
  },
];```

Thank you! I ended up using something similar to this:

/**
 * `restrict-public-access` middleware
 */

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

export default (config, { strapi }: { strapi: Strapi }) => {
  const apis = strapi.container.get('apis').getAll()
  Object.entries<any>(apis).forEach(([apiName, apiConfig]) => {
    Object.entries<any>(apiConfig.routes).forEach(([routeGroupName, routeGroupConfig]) => {
      routeGroupConfig.routes.forEach(route => {
        route.config.middlewares = [
          'global::restrict-api-access',
          ...route.config.middlewares || [],
        ]
      })
    })
  })
};

So 2 middleware: First one, is registered globally and only runs during app initialization to inject the other middleware on all API routes. Similarly, It should also be possible to inject policies.

Amazing, glad you got it working. We’d appreciate it if you could find some time to write a blog post about what you’ve done and submit it to our <#843965836887851078> channel :+1: