How to Implement HSTS into your Hydrogen Project


HSTS is HTTPS Strict-Transport-Security. It enforces that only HTTPS is used across your web application, preventing unencrypted traffic being monitored and collected by unwanted entities.
HSTS in Hydrogen
It can be enabled in your Hydrogen app via response headers. These response headers are found in your entry.server.js file. At the bottom of the handleRequest
function in the entry.server.js file, you will see lines like so:
responseHeaders.set('Content-Type', 'text/html');
responseHeaders.set('Content-Security-Policy', header);
These lines of code control the headers that are returned with the page content to the users. We can add some headers to ensure HSTS, making sure the application delivered to the client’s machine ONLY sends encrypted traffic through HTTPS
Adding the HSTS Headers
// HSTS header
responseHeaders.set(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload',
);
// BONUS: Prevent content sniffing
responseHeaders.set('X-Content-Type-Options', 'nosniff');
The max-age means the amount of time (in seconds) that the browser should enforce the HTTPS-only policy for the domain, the includeSubDomains tells us that the policy applies to all subdomains of the specified domain, and preload denotes that the domain can be included in browsers' HSTS preload lists to enforce HTTPS by default without the user visiting the site first.
And at the bottom, I also added a simple extra header to prevent content sniffing!
Subscribe to my newsletter
Read articles from David Williford directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

David Williford
David Williford
I am a developer from North Carolina. I have always been fascinated by the internet, and scince high school I have been trying to understand the magic behind it all. ECU Computer Science Graduate