Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

324
Vistas
Strapi backend broken when enable custom middleware

I created a custom middleware that makes the api & admin unreachable when I enable it.

The middleware is pretty simple, it adds a request id to incoming request on the server:

const { createNamespace } = require('cls-hooked');
const { v4: uuidv4 } = require('uuid');

const loggerNamespace = createNamespace('logger');

module.exports = (strapi) => {
  return {
    initialize() {
      strapi.app.use((ctx, next) => {
        const reqId = ctx.request.get('X-Request-Id') || uuidv4();

        ctx.response.set('X-Request-Id', reqId);

        loggerNamespace.run(() => {
          loggerNamespace.set('requestId', reqId);

          next();
        });
      });
    },
  };
};

It's enable using the config file ./config/middleware.json:

module.exports = {
  settings: {
    addRequestId: {
      enabled: true,
    },
  },
};

Then, when enabled, calling an API endpoint or trying to connect to admin results in 404 Not Found.

I use strapi 3.6.8 with node 14.18.1.

Any idea why?

PS: I suspected cls-hooked to be the culprit but removing it for testing with an anemic middleware doesn't work either.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

@Salvino put me on the right track suggesting that I should await the execution of next.

Digging in the code of cls-hooked, I found the method runPromise that is similar to run and returns a Promise that can be awaited. It solved the issue.

Fixed code:

const { createNamespace } = require('cls-hooked');
const { v4: uuidv4 } = require('uuid');

const loggerNamespace = createNamespace('logger');

module.exports = (strapi) => {
  return {
    initialize() {
      strapi.app.use(async (ctx, next) => {
        const reqId = ctx.request.get('X-Request-Id') || uuidv4();

        ctx.response.set('X-Request-Id', reqId);

        await loggerNamespace.runPromise(async () => {
          loggerNamespace.set('requestId', reqId);

          await next();
        });
      });
    },
  };
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda