Serve a pre-compressed gzipped file in express.js (not with compress() )

Viewed 4081

I'm looking to serve a gzipped file, however all approaches i have currently followed or come up with don't seem to have any effect.

I have a gzipped file with a gz extension in my static assets folder.

Currently I have used the following:

router.get("*.js", (req, res, next) => {

    // only if file exists, the substr is to remove /assets in front
    if (!fs.existsSync(`/app/service/public/${req.url.substr(7)}.gz`)) {
        return next();
    }

    console.log(`${req.url} -> ${req.url}.gz`);

    req.url = `${req.url}.gz`;
    res.set("Content-Encoding", "gzip");
    res.set("Content-Type", "text/javascript");
    next();
});

router.use("/assets", express.static("/app/service/public"));

The file exists and the directory is correctly set, but for someway it doesn't seem to serve the gzip file (neither does it add the correct headers)

2 Answers

The issue is your static middleware setup, which is pointing to the wrong path.

Given the information in your comment:

  • the .js.gz files are stored in ../public/assets/static/js/
  • you are requesting /assets/static/js/bundle.js, which should use the file called bundle.js.gz in aforementioned directory

This means that you need to use one of two static middleware configurations:

app.use('/assets', express.static(__dirname + '/../public/assets'));

Or:

app.use(express.static(__dirname + '/../public/'))

I recommend express-static-gzip which does exactly what you asked for.

app.use("/", expressStaticGzip("/my/rootFolder/"));

Also, you may specify different options, but the default will work in your case.

Related