Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Sessions and Authentication

CSRF and Security

Secure a Remix or React Router app: CSRF tokens and SameSite cookies, rate limiting, input validation, escaping and XSS, security headers and secrets that stay on the server.

Sessions and logins give attackers something worth attacking. This lesson covers the handful of web security topics that matter most in a Remix or React Router framework-mode app, what the framework already does for you, and what you must add. The runnable blocks are plain JavaScript models of the defenses.

What the framework gives you

  • Escaping by default. React escapes text in JSX, so {user.name} cannot inject markup. The danger returns only with dangerouslySetInnerHTML.
  • Server-only code. Files ending in .server.ts and the code only used by loaders and actions are removed from the browser bundle, so database passwords and API keys stay on the server.
  • Real HTTP semantics. Actions run for POST, PUT, PATCH and DELETE; loaders for GET. A page that only reads data cannot change state by accident, as long as you respect that split.

Cross-Site Request Forgery tricks a signed-in user's browser into sending a request they did not intend. If evil.example contains a hidden form that posts to https://yourapp.example/account/delete, the browser may attach your session cookie, and the server cannot tell the request was forged.

Two layers stop it:

  1. SameSite=Lax (or Strict) cookies. Browsers will not attach a Lax cookie to cross-site POSTs. This single attribute removes most CSRF risk in modern browsers, which is why the session helpers use it.
  2. Check the origin or a token. For extra safety, compare the Origin header with your own host on every non-GET request, or embed a per-session token in each form and verify it in the action.
TSX
// app/csrf.server.ts (read-only)
export function assertSameOrigin(request: Request) {
  if (request.method === "GET" || request.method === "HEAD") return;
  const origin = request.headers.get("Origin");
  const host = new URL(request.url).origin;
  if (!origin || origin !== host) {
    throw new Response("Cross-site request blocked", { status: 403 });
  }
}

Call it at the top of each action (or in a shared wrapper). Never use GET for anything that changes state, since SameSite=Lax still sends cookies on top-level GET navigations.

Node.js Stand-in: origin check and a CSRF token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

XSS: injected script

Cross-Site Scripting happens when untrusted text becomes executable markup. JSX protects you until you opt out. If you must render user-supplied HTML (for example Markdown output), sanitize it on the server with a maintained library and an allow-list, not with a regular expression. Also be careful with href values: javascript:alert(1) is a valid URL scheme, so only render links whose protocol you have checked.

Node.js Stand-in: escaping and URL checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Validate every input on the server

Treat everything in request.formData(), params and the URL as hostile. Check type, length and shape, then use parameterized queries (never build SQL by joining strings). A schema library such as Zod gives readable errors; the principle is the same with hand-written checks, and you should return field errors from the action as in the forms lessons.

Rate limiting

Login, signup and password reset endpoints invite brute force. Count attempts per IP address and per account in a fast store and respond with 429 Too Many Requests and a Retry-After header once a limit is passed.

Node.js Stand-in: a sliding-window rate limiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Security headers

Set a few headers on every response. In framework mode export headers from the root route, or use your server or CDN:

Header Purpose
Content-Security-Policy restricts where scripts and styles may load from, a strong XSS backstop
Strict-Transport-Security tells browsers to use HTTPS only
X-Content-Type-Options: nosniff stops MIME sniffing
Referrer-Policy: strict-origin-when-cross-origin limits what URL data leaks to other sites
Permissions-Policy switches off browser features you do not use

A strict CSP needs a nonce for the inline scripts the framework emits; pass it through entry.server.tsx.

Secrets and dependencies

Keep secrets in environment variables read in .server modules, never in code or in loader return values (everything a loader returns is sent to the browser). Rotate them when people leave. Run npm audit in CI and update dependencies regularly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which cookie attribute is the main modern defense against CSRF?

    SameSite stops browsers from attaching the cookie to cross-site POSTs. An Origin check or token adds a second layer.
  2. 2. Everything a loader returns is...

    Loader data is embedded in the HTML and the data requests. Return only what the page needs.
  3. 3. Why is rendering a user-provided URL in href risky?

    Only allow http, https or mailto (or relative paths).
  4. 4. What status should a rate-limited login attempt receive?

    429 Too Many Requests tells clients to slow down, and Retry-After says when to try again.

Summary

  • React escapes JSX output; sanitize any HTML you insert yourself and check URL schemes.
  • Use SameSite cookies plus an Origin or token check on every non-GET action; never change state on GET.
  • Validate all input on the server and use parameterized queries.
  • Rate limit sensitive routes, send security headers, keep secrets in .server code.

Next: Streaming with Promises