All files / server/src/middleware wwwRedirect.ts

46.15% Statements 6/13
50% Branches 2/4
100% Functions 1/1
46.15% Lines 6/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31      39x         5223x   5223x           5223x   5223x                   5223x    
import { Request, Response, NextFunction } from "express";
import { logger } from "server/utils/logger";
 
export const wwwRedirect = (
  req: Request,
  res: Response,
  next: NextFunction,
): void => {
  const host = req.get("host");
 
  Iif (!host) {
    next();
    return; // Not actually reached but required by TS
  }
 
  // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
  const hostHasWww = /^www\./.test(host);
 
  Iif (hostHasWww) {
    logger.info("Redirect WWW to non-WWW host");
 
    const protocol = req.protocol;
    const hostWithoutWww = host.replace(/^www\./, "");
 
    res.redirect(301, `${protocol}://${hostWithoutWww}${req.url}`);
    return;
  }
 
  next();
};