How to Secure a Website: 12 Practical Steps
A practical website security checklist: HTTPS, safe password storage, input validation, XSS and CSRF defences, security headers, access control and secrets.
· 10 min read
Most websites are not broken into by a brilliant new attack. They are broken into through a well-known gap that nobody closed: an out-of-date library, a query built from user input, a page that forgot to check who was asking.
This guide lists twelve steps that close those gaps. They are ordered roughly from "do this first" to "do this once the basics are in place", and each one says what the risk is and what to do about it. The code examples use Node.js, but every step applies to any language.
1. Serve everything over HTTPS
Without HTTPS, anyone on the same network can read and change what travels between the browser and your server, including passwords and session cookies.
- Get a certificate. Most hosts issue one for free and renew it automatically.
- Redirect every
http://request tohttps://. - Send the HSTS header, which tells the browser to refuse plain HTTP for your site from now on:
Strict-Transport-Security: max-age=31536000; includeSubDomainsStart with a short max-age while you test, because a browser that has seen this header will not load the site over HTTP until the time runs out.
2. Keep software and dependencies up to date
A typical project depends on hundreds of packages it did not write. When a vulnerability is found in one of them, the fix is usually a version bump, and attackers scan for sites that have not applied it.
- Run your package manager's audit command regularly, for example
npm audit. - Turn on automated update pull requests in your code host.
- Remove packages you no longer use. Code that is not there cannot be exploited.
- Keep the server's operating system, runtime and database patched as well.
3. Never trust input: validate it on the server
Everything that arrives from a browser can be forged: form fields, query strings, headers, cookies and uploaded files. Validation in the browser improves the experience for honest users, but an attacker simply skips it and sends the request directly.
Validate on the server, and be strict about what you accept:
- Check the type, length, format and range of every value.
- Prefer an allow list ("must be one of these values") over a block list ("must not contain these characters").
- Reject input that fails. Do not try to repair it.
function parseAge(value) {
const age = Number(value);
if (!Number.isInteger(age) || age < 0 || age > 150) {
throw new ValidationError("Age must be a whole number from 0 to 150");
}
return age;
}For file uploads, also limit the size, check the real file type and not just the extension, generate the stored file name yourself, and keep uploads outside the folder your web server executes code from.
4. Use parameterised queries
SQL injection happens when user input is glued into a query string. The database cannot tell which part was meant as data, so input such as ' OR '1'='1 changes the meaning of the query.
// Dangerous: the input becomes part of the SQL
db.query(`SELECT * FROM users WHERE email = '${email}'`);
// Safe: the input is sent separately and is only ever treated as a value
db.query("SELECT * FROM users WHERE email = $1", [email]);Parameterised queries, also called prepared statements, are the fix. Query builders and ORMs use them for you, as long as you do not drop back to string concatenation for "just this one query". The same rule applies to anything that builds a command from input: shell commands, file paths and NoSQL queries.
5. Stop cross-site scripting by encoding output
Cross-site scripting (XSS) is when an attacker gets their own JavaScript to run in your page, for example by posting a comment containing a <script> tag that your site then shows to other visitors. That script can act as the logged-in user.
The core defence is to treat user content as text, never as HTML:
- Let your framework or template engine escape values, which most do by default.
- Avoid the escape hatches:
innerHTML,dangerouslySetInnerHTML,v-htmland similar. - If you must show user-written HTML, pass it through a well-maintained sanitiser first.
The full explanation, with examples of each kind of XSS, is in XSS and CSRF explained.
6. Store passwords with a slow hash, and add a second factor
If your database leaks, the attacker should not get usable passwords.
- Never store passwords as plain text, and never with a fast hash such as MD5 or SHA-256. Fast hashes let an attacker try billions of guesses per second.
- Use an algorithm designed for passwords: Argon2id, or bcrypt or scrypt where Argon2id is not available. They are deliberately slow and add a unique salt to each password.
- Use a maintained library and its recommended settings. Do not write your own.
import argon2 from "argon2";
const hash = await argon2.hash(password); // when the user signs up
const matches = await argon2.verify(hash, password); // when they log inThen make stolen passwords less useful:
- Offer multi-factor authentication, and require it for administrator accounts.
- Rate-limit login attempts per account and per IP address.
- Give the same answer for "wrong email" and "wrong password", so the form cannot be used to discover which accounts exist.
7. Lock down cookies
A session cookie is as good as a password while it is valid. Three attributes protect it:
res.cookie("session", sessionId, {
httpOnly: true, // JavaScript in the page cannot read it
secure: true, // sent only over HTTPS
sameSite: "lax", // not sent on most requests started by other sites
maxAge: 1000 * 60 * 60 * 8, // expires after 8 hours
});| Attribute | What it protects against |
|---|---|
HttpOnly |
A script injected by XSS reading the cookie |
Secure |
The cookie being sent over an unencrypted connection |
SameSite |
Other sites making requests that carry the cookie |
Also create a new session ID when the user logs in, and destroy the session on the server when they log out. Deleting the cookie in the browser is not enough, because a stolen copy would still work.
8. Protect state-changing requests from CSRF
Cross-site request forgery (CSRF) tricks a logged-in user's browser into sending a request to your site from somewhere else. Because the browser attaches cookies automatically, your server sees a valid session.
- Set
SameSite=LaxorStricton session cookies. - Require an anti-CSRF token on every request that changes something. Most web frameworks include this.
- Never change data in response to a
GETrequest.
9. Add security headers
A few response headers switch on protections that are built into every browser.
| Header | What it does |
|---|---|
Content-Security-Policy |
Limits where scripts, styles and other resources may load from. The strongest defence in depth against XSS. |
X-Content-Type-Options: nosniff |
Stops the browser guessing a file's type and running it as script |
X-Frame-Options: DENY |
Stops other sites showing yours in a frame, which blocks clickjacking. frame-ancestors in the content security policy is the modern equivalent. |
Referrer-Policy: strict-origin-when-cross-origin |
Stops full URLs leaking to other sites |
Permissions-Policy |
Switches off browser features you do not use, such as the camera |
A reasonable starting content security policy is:
Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'Tighten it from there. Roll it out with Content-Security-Policy-Report-Only first, so you can see what it would block without breaking the site.
10. Check permissions on the server, on every request
Broken access control is the most common serious flaw in web applications, and it ranks first in the OWASP Top 10. It usually looks like this: the page hides the "Delete" button from ordinary users, but the server endpoint behind the button never checks who is calling it.
// Dangerous: any logged-in user can read any invoice by changing the ID
app.get("/invoices/:id", async (req, res) => {
res.json(await db.invoices.find(req.params.id));
});
// Safe: the invoice must belong to the person asking
app.get("/invoices/:id", async (req, res) => {
const invoice = await db.invoices.find(req.params.id);
if (!invoice || invoice.ownerId !== req.user.id) {
return res.status(404).end();
}
res.json(invoice);
});- Deny by default, and grant access explicitly.
- Check both who the user is and whether this record is theirs.
- Do the check on the server. Hiding a link or a button is not security.
11. Keep secrets out of your code
API keys, database passwords and signing keys do not belong in the repository. Anyone who can read the code, including everyone who ever cloned it, can read them, and they stay in the history after you delete them.
- Load secrets from environment variables or a secrets manager.
- Add local secret files such as
.envto.gitignore. - Anything shipped to the browser is public. A key in front-end JavaScript is not a secret.
- If a secret is ever committed or leaked, rotate it. Removing it from the code does not un-leak it.
- Give each key the least access that works: a read-only database user for a reporting job, for example.
12. Log, monitor and back up
You cannot respond to an attack you cannot see, and you cannot recover without a copy of your data.
- Log sign-ins, failed sign-ins, permission failures and changes to accounts.
- Never log passwords, tokens or full card numbers.
- Alert on unusual patterns, such as a burst of failed logins.
- Show users a generic error page. Stack traces and database errors help attackers map your system.
- Take automatic backups, store them somewhere separate, and practise restoring one. An untested backup is only a hope.
A quick way to check your site
Free scanners catch the easy mistakes in a minute:
- Mozilla HTTP Observatory grades your security headers.
- SSL Labs Server Test checks your HTTPS configuration.
- Your browser's developer tools show the cookies and headers a page actually receives.
These tools check configuration, not your application's logic. They will not find a missing permission check, so they are a starting point and not a substitute for the steps above.
Summary
| Step | The one-line version |
|---|---|
| 1. HTTPS | Encrypt everything and send HSTS |
| 2. Updates | Patch dependencies and servers |
| 3. Validation | Check every input on the server |
| 4. Queries | Parameterise, never concatenate |
| 5. XSS | Treat user content as text |
| 6. Passwords | Argon2id or bcrypt, plus a second factor |
| 7. Cookies | HttpOnly, Secure, SameSite |
| 8. CSRF | SameSite cookies and anti-CSRF tokens |
| 9. Headers | Content security policy and friends |
| 10. Access control | Check permissions on every request |
| 11. Secrets | Out of the code, rotated when leaked |
| 12. Operations | Log, monitor and back up |
If your site lets people sign in through an API, continue with access tokens and refresh tokens explained and the access token best practices.
Further reading
- OWASP Top 10: the most common web application risks.
- OWASP Cheat Sheet Series: detailed guidance for each topic above.
- OWASP Password Storage Cheat Sheet: current algorithm settings.
- MDN: Content Security Policy: how to write and test a policy.