Ctx.state not populated in strapi V4 middleware

System Information
  • Strapi Version: 4.2.0
  • Operating System: Linux Mint 20.2
  • Database: PostgreSQL 12.9
  • Node Version: 14.19.3
  • NPM Version: 6.14.17
  • Yarn Version: 1.22.19

Hello everyone

As the title says, ctx.state is an empty object in my solution when I’m navigating admin panel routes as I need to pre-populate some values based on the user for them to be checked further in user-conditions.

// src/middlewares/foo-middleware.js

module.exports = (config, { strapi }) => {
  // Add your own logic here.
  return async (ctx, next) => {
    // this is empty
    console.log('ctx.state', ctx.state)
    strapi.log.info('In foo-middleware middleware.');

    await next();
  };
};

// config/middlewares.js
module.exports = ({ env }) => [
  'strapi::errors',
  {
    name: 'strapi::security',
    config: {
      contentSecurityPolicy: {
        directives: {
         
        },
      },
    },
  },
  {
    resolve: 'src/middlewares/cors-options',
    config: {
      enabled: true,
    },
  },

  {
    name: 'strapi::cors',
    config: {
      header: '*',
      origin: ['*'],
      enabled: true,
    },
  },
  'strapi::poweredBy',
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
  {
    resolve: 'src/middlewares/foo-middleware',
    config: {
      enabled: true,
    },
  },
];

I want to ask you if there could be something I’m missing?

Thanks!

1 Like

Hello @radu.m ,

we had the same problem today and saw your post. So if you still have issues encountering your problem, try to move “await next ()” above your console.log, like this:

module.exports = (config, { strapi }) => {
  // Add your own logic here.
  return async (ctx, next) => {
   await next(); 
    // this is empty
    console.log('ctx.state', ctx.state)
    strapi.log.info('In foo-middleware middleware.');
  };
};
1 Like

But here the specific action will already be performed by the time state is populated.
Is there a way to know the state before we go for “await next()”