Adding HSTS Headers

Viewed 771

I need to add a HSTS header to this file , but I am unsure of how to do it.

import { injectable, inject } from 'tsyringe';
import { NextFunction, Request, Response } from 'express';

import * as Types from '../../types';

@injectable()
class EncryptionController {

  constructor(@inject('EncryptionService') private service: Types.EncryptionService) { }

  public encrypt = async (req: Request, res: Response<Types.EncryptResponsePayload | Types.ServiceError>, next: NextFunction) => {
    try {
      
      const { publicKeys, payload } = req.body as Types.EncryptRequest;
      const response = await this.service.encrypt(payload, publicKeys);
      
      res.status(200).json(response);
    } catch (error) {
      if (error.message === 'not found' || error.message === 'Secret not found') {
        res.status(404).json({ message: error.message });
      } else {
        res.status(400).json({ message: error.message });
      }
    }
  }

I would appreciate any direction on this

1 Answers

In the response, you can call res.setHeader(headerName, headerValue) to set any header, including HSTS headers. Typically you'll want to do something like:

res.setHeader('Strict-Transport-Security', 'max-age=3600; includeSubDomains');

That enables HSTS for 1 hour - this is a good value for a first test, but you should probably increase it to something like 31536000 (1 year) once you've confirmed that everything works correctly.

You need to put that somewhere before your res.status()... lines to set this header.

This enables HSTS for the entire site and other subdomains, but only once the client requests this specific endpoint. In most cases, assuming you have many other endpoints, you want to send HSTS response headers in all responses. To do so, you can use express middleware to add these headers. You can write that yourself, or you can use Helmet (e.g. app.use(helmet.hsts())) which can do this and many other good security practices for you globally & easily.

Related