Execute middleware for only Content type APIs

How can I let Strapi execute a custom middleware only for APIs and not for admin panel ?

Hey @Farhan_Shaikh,

If I’m correct you can’t specify it for admin or api.
But you could check for the admin object in ctx.state, something like this:

module.exports = strapi => {
  return {
    // can also be async
    initialize() {
      strapi.app.use(async (ctx, next) => {
        if(!ctx.state.admin) {
          // await someAsyncCode()
        }

        await next();

        // await someAsyncCode()
      });
    },
  };
};

Hope this helps! :+1:

Hi @MattieBelt thanks for your suggestion, I tried implementing it but it didn’t work. Below is my middleware I’m trying to customize API data response using this middleware. Its working for APIs but its also executing for Admin panel too.

module.exports = strapi => {
    return {
        initialize() {
            strapi.app.use(async (ctx, next) => {
                let response = {};
                await next();
                if (ctx.response.status === 200) {
                    response.status = 'success';
                    response.data = ctx.response.body;
                }
                else {
                    response.status = 'error';
                }
                ctx.response.body = response;
            });
        },
    };
};

Hi @Farhan_Shaikh, may I ask why you want to send the status in text, instead of a number?
Isn’t this something for the front-end to handle? And does console.log(ctx.state.admin); print undefined?

Hi @MattieBelt, yes console.log(ctx.state.admin); is always returning undefined.
Whereas I want to customize the API response on success it should return { status: "success", data: strapi_api_response_here } while for error response { status: "error", error: strapi_api_error_response_here }

you can manipulate using:

let { url } = ctx.request
if (url.indexOf('admin') < 0) {
//your logic for API
//asynx next();
}
else{
asynx next();
}

but carefull, you can using “admin” in the API routers

1 Like