How to access ctx.state.user in a global middleware [strapi v4.14]

System Information
  • Strapi Version: 4.14
  • **Operating *:Windows 11 Home
  • Database: Sqlite
  • Node Version: 18.17.1
  • NPM Version: 9.6.7

I’ve edited a global middleware which gets author data to each operations to make some verifications. but I don’t access to ctx.state.user in that middleware.

module.exports = (config, { strapi }) => {
    return async (ctx, next) => {
        console.log(ctx.state.user);

        return next();
    };
};

I’ve tried to access it even in some lifecycle files, but it’s the same thing.

When I console.log(ctx.state), it returns {} an empty object so I cannot access to ctx.state.user

Documentation didn’t help me

beforehand thanks for any help

2 Likes

Same problem, I want to restrict the media library to authenticated users, but I have the impression that our middleware loads before the session middleware.

export default (_config, { strapi }) => {
    return async (ctx, next) => {
        if (ctx.method === 'GET') {
            if (ctx.url.startsWith('/uploads/')) {
                console.log('ctx.state', ctx.state)
                console.log('ctx.state.user', ctx.state.user)
                console.log('ctx.state.auth', ctx.state.auth)
                console.log('ctx.state.isAuthenticated', ctx.state.isAuthenticated)
                if (!ctx.state.user) {
                    // Rediriger vers une autre route
                    return ctx.redirect('/admin/auth/local');
                }
            }
        }
        await next();
      };
};

Same issue, @DMehaffy?