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

181 Views Asked by At

I've edited a global middleware which gets author data to each operations to make some verifications. But I don't have 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

Thanks in advance for any help

2

There are 2 best solutions below

0
Minghao On

The answer is from Jwt token.

const { id } = await strapi.plugins['users-permissions'].services.jwt.getToken(ctx);
const user = await strapi.entityService.findOne('plugin::users-permissions.user', id, {
  populate: '*',
});
0
Antonio On

Try to modify your code like this:

module.exports = (config, { strapi }) => {
    return async (ctx, next) => {
        await next();

        console.log(ctx.state.user);
    };
};