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

342
Visualizações
How to conditionally include a sub-app with Express?

I'm using a library called Grant in my application. Previously I have included it following the examples in the readme linked above, however I now have the need to conditionally include it and I can't seem to make it work.

How it worked before

const grant = new Grant(grantConfig);
app.use(grant);

I've done conditional middleware in Express before, so I thought including Grant wouldn't be a problem.

How I Tried (doesn't work)

const grant = new Grant(grantConfig);

app.use((req, res, next) => {
    if (someBooleanVariable) {
        next();
    } else {
        grant(req, res, next);
    }
});

So this doesn't work. I think it may have something to do with Grant being an instance of Express versus just a regular middleware function, but I'm not sure. You can see how Grant is implemented here. The Express docs say that it should be treated the same, but I might also be misunderstanding them.

Note: I need this to work on per-request basis, hence the middleware style approach.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you want to use a particular middleware on only a subset of routes:

// On a single route:
app.get('/some/route', grant, function(req, res) {
  ...
});

// On a set of routes with a particular prefix:
app.use('/api', grant, apiRouter);

// On a specific router:
let apiRouter = express.Router();

apiRouter.use(grant);
apiRouter.get(...);
about 4 years ago · Santiago Trujillo 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