Explain Codes LogoExplain Codes Logo

How can I set response header on express.js assets

javascript
express-engineering
middleware
headers
Anton ShumikhinbyAnton Shumikhin·Nov 3, 2024
TLDR

The nitty-gritty for setting HTTP headers for assets in Express.js is effectively done by a middleware. It applies the res.set() method right before dispatching files. To ensure that your custom header accompanies all requests for assets, emulate this snippet:

app.use('/assets', (req, res, next) => { res.set('Give-Me', 'Cookies'); // Express urge for cookies here next(); }, express.static('public'));

This code injects "Give-Me": "Cookies" header (who doesn't love cookies?) into responses serving static assets from the stirring 'public' directory.

Custom header scenarios

There may be times when you'll require specific headers for several scenarios. Here's how we handle those curveballs.

CORS handling made easy

Cross-Origin Resource Sharing (CORS) can be a tough nut to crack. The cors middleware eases this hurdle with its versatile configuration options:

const corsOptions = { origin: 'https://my.favorite.site', // Favorite site because why not? optionsSuccessStatus: 200, // Optimists aim for 200 }; app.use('/assets', cors(corsOptions), express.static('public'));

Efficient caching techniques

Guide the caching of your assets by taking charge of your Cache-Control headers:

app.use('/assets', (req, res, next) => { res.set('Cache-Control', 'public, max-age=86400'); // The more the merrier, until max-age infinity next(); }, express.static('public'));

Security++ with headers

Boost your app's guard by using security-oriented headers like Content-Security-Policy (CSP). Have the helmet module take care of it:

const helmet = require('helmet'); app.use(helmet.contentSecurityPolicy()); // Don the helmet app.use('/assets', express.static('public'));

Performance-geared headers

App performance matters. The way you govern headers can influence it heavily. Aim for optimization when setting headers for a large number of operations and specific requests.

Setting headers collectively

For setting several headers, feed an object into res.set:

app.use('/assets', (req, res, next) => { res.set({ 'Child-One': 'ValueOne', // One header child is named 'Child-One' 'Child-Two': 'ValueTwo', // Two header children create more fun // ...and they lived happily ever after }); next(); }, express.static('public'));

Dynamic headers for dynamic tasks

In a mutable environment, dynamic headers comes in handy. Modify headers based on request properties:

app.use('/assets', (req, res, next) => { res.set('Super-Powered-By', 'Express'); // Powered up to Super level if (req.is('json')) { res.set('Content-Type', 'application/json'); // Spidey-sense for json } next(); }, express.static('public'));

Custom files for custom folks

Serve customized files using tailored middleware based on factors like user agents:

app.use('/assets', (req, res, next) => { if (req.headers['user-agent'].includes('Mobile')) { res.set('Content-Type', 'text/css'); // Mobile user, you're in for a treat express.static('public/mobile')(req, res, next); } else { express.static('public/desktop')(req, res, next); // Desktop user, we've got your back too } });