Home > Net >  Modified Req Url in Express middleware ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent
Modified Req Url in Express middleware ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent

Time:09-13

Hey guys I am facing the error Error "[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" when I am trying to modify the req.url in a express middleware.

My middleware

export function ModifyQueryMiddleware(config, Authconfig, Repo ){
    const accessTokenMap = new Map();
    return async (request, res, next) => {
        
        const accessToken = request.header('authorization') as string;
        if(!accessToken){
            throw new HttpException(res, 403)
        }

        if(!accessTokenMap.get(accessToken)){
            const JWKS = jose.createRemoteJWKSet(new URL(config.jkwsUri));
            try {
                const jwtVerifyResult = await jose.jwtVerify(accessToken.replace('Bearer ', ''), JWKS);
                const {payload} = jwtVerifyResult;

                accessTokenMap.set(accessToken, payload)

                const aumParams = await authentication(payload, authConfig,Repo); 
               
                const queryRestrictionStrategy = QueryRestrictionStrategyFactory(aumParams, request)
                queryBuilder(queryRestrictionStrategy)
                next()
            } catch(err){
                
            }
        }

        const payload = accessTokenMap.get(accessToken);
        const aumParams = await authentication(payload, authConfig, repo);
        const queryRestrictionStrategy = QueryRestrictionStrategyFactory(aumParams, request)
        queryBuilder(queryRestrictionStrategy)
        next()      
        
    }
}

My queryBuilder:

export function queryBuilder(strategy: QueryRestrictionStrategy){
    const {req, id} = strategy
    if(req.url === '/someurl'){
        req.url = `/someurl?${id}`
    }
    return 
}

I am really confused as I don't modify the header of a response instead I am just modifying the query without the querybuilder the middleware works fine. I already looked at a few questions regarding this error however the res was there always modified.

Any help or tips would be really appreciated !

CodePudding user response:

Your code can call next twice when !accessTokenMap.get(accessToken) is true. You have to return once that part of your code is handled:

if (!accessTokenMap.get(accessToken)) {
  const JWKS = jose.createRemoteJWKSet(new URL(config.jkwsUri));
  try {
    ...
    next();
  } catch(err) {
    next(err); // make sure to pass the error along!
  }
  return;
}
  • Related