Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

323
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda