How can I differentiate between a request coming from the content-manager (in admin end) and API request in front-end when hooking into the life-cycle methods

I’ve tried several ways on how to differentiate request coming from the content-manager in admin and API request on front-end by getting the request object using (strapi.app.callback()()), but that through an error that the ‘url’ is undefined inside any of the life-cycle hooks, don’t know why.

So am curious if it’s possible to actually know a request is from the admin end by using any Strapi utility methods.

Hi! Does anybody know a proper way to do this? I solved this by checking if any of my event?.params?.data values that are a relation have a connect property.
Like so:

if (!event?.params?.data?.term?.connect) {
 // backend
} else {
 // frontend
}

But this feels like a hack and does not work if you have no relations in your data…

Quite a late answer, but I think that

const ctx = strapi.requestContext.get()

should do the trick.

If it comes from the web there is a context, if it’s from the entityService or db.query it’s undefined :slight_smile:

However, this does not differentiate between content manager or API.

The way I solved that problem is with the following middleware:

import { Strapi } from '@strapi/strapi'
import jwt from 'jsonwebtoken'

export default (_index, { strapi }: { strapi: Strapi }) => {
  return async (ctx, next) => {
    if (!ctx.request.url.startsWith('/content-manager')) {
      ctx.state.isAdminUI = false
      return await next()
    }

    if (!ctx.request.header.authorization) {
      ctx.state.isAdminUI = false
      return await next()
    }
    const token = ctx.request.header.authorization.split(' ')[1]

    if (!token) {
      ctx.state.isAdminUI = false
      return await next()
    }

    const { secret } = strapi.config.get('admin.auth', {}) as any
    try {
      jwt.verify(ctx.request.header.authorization.split(' ')[1], secret)
      ctx.state.isAdminUI = true
    } catch {
      ctx.state.isAdminUI = false
    }

    await next()
  }
}

This middleware eventually checks if the authorization token of the request can be decoded with the admin auth secret.