The last lesson was about attacks on your logic. This lesson is about the settings and habits around your code that decide whether an attack succeeds: where secrets live, whether traffic is encrypted, which headers you send, and whether the packages you installed have known holes. None of it is difficult, and all of it is routinely skipped. A short checklist done once is worth more than any clever code.
Secrets and environment variables
- Keep secrets such as database passwords, JWT keys and API keys out of Git. Put them in environment variables, loaded from a
.envfile in development, and make sure.envis listed in.gitignore. - If a secret is ever committed, treat it as stolen, even if you delete it afterwards, because Git keeps history. Change it at the provider.
- Use a different secret in each environment, and make them long and random.
- On a server, set them in the host's settings or a secrets manager rather than a file in the project.
Read your configuration once, at start, and check it. The example below uses Zod to require a JWT_SECRET of at least 32 characters, accepts only three values for NODE_ENV, and turns the port into a number. If something is wrong the app refuses to start with a clear message, which is far better than starting and failing at three in the morning.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install express helmet jsonwebtoken zod. - Save the code as
hardening.js. The test needsnpm install -D supertest.
import express from 'express';
import helmet from 'helmet';
import jwt from 'jsonwebtoken';
import { z } from 'zod';
// Read and check the settings once, at start. Crash early with a clear message, not later with a mystery.
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
JWT_SECRET: z.string().min(32, 'JWT_SECRET must be at least 32 characters'),
});
export const loadEnv = (source = process.env) => envSchema.parse(source);
// JWT best practice: fix the algorithm, issuer and audience when you SIGN and when you VERIFY.
export const signToken = (payload, secret) =>
jwt.sign(payload, secret, { algorithm: 'HS256', expiresIn: '15m', issuer: 'my-api', audience: 'my-app' });
export const verifyToken = (token, secret) =>
jwt.verify(token, secret, { algorithms: ['HS256'], issuer: 'my-api', audience: 'my-app' });
export function createApp() {
const app = express();
app.disable('x-powered-by');
app.use(helmet()); // sets many security headers at once
app.get('/', (req, res) => res.json({ ok: true }));
return app;
}
JWT best practices
The two functions signToken and verifyToken hold the rules. Fix the algorithm in both places. Some older attacks worked because a library accepted whatever algorithm the token claimed, including none, which means no signature at all. Set an issuer and an audience so a token made for another service is not accepted by yours. Use a short expiry. Keep the payload small and never put secrets in it, because a JWT is signed but not encrypted; anyone can read it. The test proves that a token with the none algorithm, a token with the wrong audience and a token signed with another secret are all refused.
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import jwt from 'jsonwebtoken';
import { createApp, loadEnv, signToken, verifyToken } from './sec32-hardening.js';
const SECRET = 'a-long-random-secret-with-32-chars!!';
test('helmet headers and no x-powered-by', async () => {
const res = await request(createApp()).get('/');
assert.equal(res.headers['x-powered-by'], undefined);
assert.equal(res.headers['x-content-type-options'], 'nosniff');
assert.ok(res.headers['strict-transport-security']);
assert.ok(res.headers['content-security-policy']);
});
test('environment is checked at start', () => {
assert.throws(() => loadEnv({ JWT_SECRET: 'short' }), /at least 32/);
assert.equal(loadEnv({ JWT_SECRET: SECRET, PORT: '4000' }).PORT, 4000);
});
test('token checks: alg none, wrong audience and wrong secret are refused', () => {
const good = signToken({ sub: 1 }, SECRET);
assert.equal(verifyToken(good, SECRET).sub, 1);
const none = Buffer.from('{"alg":"none","typ":"JWT"}').toString('base64url') + '.' + Buffer.from('{"sub":1,"iss":"my-api","aud":"my-app"}').toString('base64url') + '.';
assert.throws(() => verifyToken(none, SECRET));
const otherAudience = jwt.sign({ sub: 1 }, SECRET, { issuer: 'my-api', audience: 'other-app' });
assert.throws(() => verifyToken(otherAudience, SECRET));
assert.throws(() => verifyToken(good, 'a-different-secret-with-32-characters!'));
});
ok 1 - helmet headers and no x-powered-by
ok 2 - environment is checked at start
ok 3 - token checks: alg none, wrong audience and wrong secret are refused
Helmet: security headers in one line
Helmet is a middleware that sets a group of HTTP headers that tell browsers to behave more safely. Among them are Strict-Transport-Security, which asks browsers to use HTTPS only, X-Content-Type-Options, which stops a browser from guessing file types, and a basic Content-Security-Policy, which limits where scripts may load from. You add it with app.use(helmet()). If your front end loads scripts or images from other sites, you may need to adjust the policy, so test the pages after turning it on.
HTTPS and CORS
HTTPS encrypts the traffic between the browser and your server, so passwords and tokens cannot be read on the way. Production sites must use it. Lesson 42 shows how to get a free certificate with Let's Encrypt. CORS is a different matter: it controls which *websites* may call your API from a browser. Do not use origin: '*' together with cookies. List the exact origins that you trust.
Dependencies
Your app contains thousands of packages that you did not write. Run npm audit regularly to list known problems, update packages in small steps, commit package-lock.json, and use npm ci in builds so that exactly the locked versions are installed. Remove packages that you do not use. Turn on Dependabot or a similar service to receive update pull requests. A package that is no longer maintained is a risk even when it has no known bug today.
Your task
- Start the app without
JWT_SECRETand read the error. - Run
npm auditin your project and read the report. - Add
helmet()to an existing app and check the response headers in your browser's network tab.
How to check it worked
- The app refuses to start with a missing or short secret.
- A token with the wrong audience is refused.
- Your
.envfile is in.gitignore.