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

176
Visualizações
Returning an array of middleware from another middleware in express JS?

I have a route to view the information of a shop. The route looks like

router.param('userId',getUserById)
router.get("/store/:storeName/:userId?",isAuthenticated,getStoreDetail)

Based on the condition I want to send a response. In the route the userId is optional. If the userId is not provided it sends only particular information of the shop as a response. And if the userId is provided then I should authenticate the user and then send all the details of the shop.

So I created a middleware to achieve this.

const isAuthenticated = (req, res, next) => {
    const { user } = req
    if (user) {
        return [
            expressJwt(jwtTokenProperty),
            (err, req, res, next) => {
                if (err) {
                    return res.status(401).json({
                        status: false,
                        error: err.message,
                        isJWTError: true
                    })
                }
                const checker = req.user && req.auth && req.user.id == req.auth.id
                if (!checker) {
                    return res.status(401).json({
                        status: false,
                        error: "Invalid Request"
                    })
                }
                next()
            }
        ]
    } else {
        next()
    }
}

If the userId is not provided then I am getting a response as needed. But if the userId is provided I don't get any response.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You forgot to return next().

Edit: You need to return a response rather than array containing a function.

const isAuthenticated = (req, res, next) => {
    const { user } = req
    return user
        ? [expressJwt(jwtTokenProperty), processResponse(req, res, next)]
        : next()
}

const processResponse = (req, res, next) => {
    const checker = req.user && req.auth && req.user.id == req.auth.id
    if (!checker) {
        return res.status(401).json({
            status: false,
            error: "Invalid Request"
        })
    }
    return 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