Skip to main content

Security and hardening · Beginner · 15 min

Prevent open redirects in sign-in and return URLs

By Padding · Updated 18 Nov 2026
node:26 image (Debian) · Node.js 26.13.1 · no npm packages

You will turn a sign-in page that sends people to any site named in its ?next= parameter into one that only returns them to your own pages or a short allow-list, with a node --test table of tricky inputs that proves it.

On this page

Most sign-in pages remember where you were going. You open /orders/42, the app sends you to /login?next=/orders/42, and once you sign in it sends you back. That next value comes from the address bar, so anyone can write it. If the app redirects to whatever it holds, a link such as https://your-app.example/login?next=https://evil.example/ starts on your real domain, shows your real sign-in page, and ends on a page the attacker controls. That page can copy your sign-in form and ask for the password "again". The flaw is called an open redirect (CWE-601).

Links like this travel well in WhatsApp groups, SMS and email, where people see only the start of the address and phones often cut off the rest. Your domain at the start of the link is the thing that earns their trust, so do not let the end of it send them elsewhere.

In this tutorial you build a small sign-in app with Node.js 26 and no npm packages, watch it send a user to another site, then write a return-URL check that:

  1. accepts paths on your own site, such as /orders/42?tab=items
  2. refuses //evil.example, /\evil.example and other inputs that browsers read as another host
  3. parses the value with the URL API against a fixed base and compares origins
  4. allows a few named external sites, matched by exact origin
  5. falls back to / for everything else

A table of tricky inputs in node --test proves each rule. The last step applies the same idea to OAuth redirect URIs. Every "attacker" site here uses the reserved .example domain, so nothing leaves your machine.

Step 1 · Build a sign-in page with a return URL

Create a throwaway folder and a package.json. Nothing gets installed: the app uses node:http, and the tests use node:test.

Bash
mkdir -p ~/redirect-demo/test
cd ~/redirect-demo
cat > package.json <<'JSON'
{
  "name": "redirect-demo",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node server.js",
    "test": "node --test"
  }
}
JSON

Now the app. GET /login shows a form that carries next in a hidden field, and POST /login "signs you in" (it skips the password check to keep the demo short) and redirects with 303 See Other. The two lines marked FLAW trust next as it arrives:

Bash
cat > app.js <<'JS'
import { createServer } from 'node:http'

const escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)

export function createApp() {
  return createServer(async (req, res) => {
    const url = new URL(req.url, 'http://localhost')

    if (req.method === 'GET' && url.pathname === '/login') {
      const next = url.searchParams.get('next') ?? '/' // FLAW: trusts next
      res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
      res.end(`<form method="post" action="/login">
  <input name="user" value="amara">
  <input type="hidden" name="next" value="${escapeHtml(next)}">
  <button>Sign in</button>
</form>\n`)
      return
    }

    if (req.method === 'POST' && url.pathname === '/login') {
      let body = ''
      for await (const chunk of req) {
        body += chunk
        if (body.length > 10_000) {
          res.writeHead(413).end()
          return
        }
      }
      const form = new URLSearchParams(body)
      // A real app checks the password here.
      res.writeHead(303, {
        location: form.get('next') || '/', // FLAW: trusts next
        'set-cookie': 'sid=demo-session; HttpOnly; SameSite=Lax; Path=/',
      })
      res.end()
      return
    }

    if (req.method === 'GET' && url.pathname === '/dashboard') {
      res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
      res.end('Dashboard\n')
      return
    }

    res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
    res.end('Not found\n')
  })
}
JS
cat > server.js <<'JS'
import { createApp } from './app.js'

const port = Number(process.env.PORT ?? 3000)
createApp().listen(port, '127.0.0.1', () => {
  console.log(`Listening on http://127.0.0.1:${port}`)
})
JS

The app is split in two on purpose. app.js builds the server without starting it, so the tests in step 5 can start their own copy on a free port. server.js starts it on port 3000. The form value is HTML-escaped, which stops a different bug (cross-site scripting through the hidden field). Escaping does nothing about where the redirect goes.

In a second terminal, start the app from ~/redirect-demo:

Bash
cd ~/redirect-demo
npm start

Check it worked

The second terminal prints Listening on http://127.0.0.1:3000. Back in the first terminal, ask for the sign-in page with a return path:

Bash
curl -s 'http://127.0.0.1:3000/login?next=/dashboard'

The form comes back with value="/dashboard" in the hidden field.

Step 2 · Watch the redirect leave your site

Sign in as a browser would after following a crafted link. -i prints the response headers, and grep keeps the Location line, which is where the browser goes next:

Bash
curl -si -X POST --data 'user=amara&next=https://evil.example/' http://127.0.0.1:3000/login | grep -i '^location'
curl -si -X POST --data 'user=amara&next=//evil.example' http://127.0.0.1:3000/login | grep -i '^location'

The second line is the one people miss. //evil.example has no https:, so it looks like a path, but a browser reads a value that starts with // as "same scheme, different host". Checking only that next "starts with a slash" lets it through.

Stop the server with Ctrl+C in the second terminal.

Check it worked

Both lines print a location: header that points at evil.example: location: https://evil.example/ and location: //evil.example. A user who clicked such a link would land on that site straight after signing in, with your domain still in their browser history.

Step 3 · Write a return-URL check

Put the rules in one small module that every redirect in the app goes through. Create safe-redirect.js:

Bash
cat > safe-redirect.js <<'JS'
// The origin this app is served from. Set APP_ORIGIN in production,
// for example APP_ORIGIN=https://app.your-domain.com
const APP_ORIGIN = new URL(process.env.APP_ORIGIN ?? 'http://localhost:3000').origin

// The only other sites a return URL may point to. Exact origins, https only.
const EXTERNAL_ORIGINS = new Set(['https://help.example.org'])

const FALLBACK = '/'

export function safeRedirect(input) {
  // 1. Only non-empty strings of a sane length.
  if (typeof input !== 'string' || input.length === 0 || input.length > 2048) return FALLBACK

  // 2. No control characters (tabs, newlines) and no backslashes, which
  //    URL parsers strip or treat as slashes.
  if (/[\u0000-\u001f\u007f\\]/.test(input)) return FALLBACK

  // 3. A path on this site: one leading slash, not two.
  if (input.startsWith('/') && !input.startsWith('//')) {
    const url = new URL(input, APP_ORIGIN)
    if (url.origin !== APP_ORIGIN) return FALLBACK
    return url.pathname + url.search + url.hash
  }

  // 4. A full URL to one of the named external sites.
  let url
  try {
    url = new URL(input)
  } catch {
    return FALLBACK
  }
  if (url.protocol === 'https:' && EXTERNAL_ORIGINS.has(url.origin) && !url.username && !url.password) {
    return url.href
  }

  return FALLBACK
}
JS

Each numbered rule closes a known trick:

  • Rule 2 refuses backslashes and control characters before any parsing. The URL standard treats \` as `/ in http and https addresses, so /\evil.example becomes //evil.example. It also removes tabs and newlines, so /<tab>/evil.example turns into //evil.example too. No real path on your site needs either.
  • Rule 3 is the string check, and it is only the first filter. The value is then parsed with new URL(input, APP_ORIGIN), and the result must have the same origin (scheme, host and port) as the app. If some input slips past the string test, the parser has the last word, and the parser behaves the way browsers do.
  • Rule 3 returns a rebuilt value: url.pathname + url.search + url.hash, never the raw input. So the Location header always holds a clean path on your site. The parser also resolves dot segments, so /reports/../settings becomes /settings.
  • Rule 4 allows full URLs only when the origin is in EXTERNAL_ORIGINS, compared as whole strings. A check such as url.hostname.endsWith('example.org') would accept evilexample.org, and includes('help.example.org') would accept help.example.org.evil.example. It also refuses a username or password in the URL, so https://me@help.example.org/ is out.
  • The fallback is a fixed path. A refused value goes to / and is never echoed back or shown as an error page that repeats it.

APP_ORIGIN comes from an environment variable, so the same code works on your laptop and on your server. It is used only as a base for parsing and as the value to compare against, so it holds no secret.

Check it worked

Call the function on three values:

Bash
node --input-type=module -e "
import { safeRedirect } from './safe-redirect.js'
console.log(safeRedirect('/orders/42?tab=items'))
console.log(safeRedirect('//evil.example'))
console.log(safeRedirect('https://help.example.org/guide'))
"

It prints /orders/42?tab=items, then /, then https://help.example.org/guide.

Step 4 · Test it against a table of tricky inputs

A redirect check is easy to break with a later "small fix", so keep its rules in a test. Each row is an input and the value the check must return:

Bash
cat > test/safe-redirect.test.js <<'JS'
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { safeRedirect } from '../safe-redirect.js'

const cases = [
  // Paths on this site are kept, in a clean form.
  ['/dashboard', '/dashboard'],
  ['/orders?id=7#top', '/orders?id=7#top'],
  ['/reports/../settings', '/settings'],
  ['/%2F%2Fevil.example', '/%2F%2Fevil.example'],
  // A named external site is allowed.
  ['https://help.example.org/guide', 'https://help.example.org/guide'],
  // Everything below falls back to the home page.
  ['https://evil.example/', '/'],
  ['//evil.example', '/'],
  ['/\\evil.example', '/'],
  ['\\\\evil.example', '/'],
  ['/\t/evil.example', '/'],
  [' //evil.example', '/'],
  ['javascript:alert(1)', '/'],
  ['data:text/html,hello', '/'],
  ['http:evil.example', '/'],
  ['http://help.example.org/', '/'],
  ['https://help.example.org.evil.example/', '/'],
  ['https://help.example.org@evil.example/', '/'],
  ['https://me@help.example.org/', '/'],
  ['', '/'],
  [null, '/'],
  ['/' + 'a'.repeat(3000), '/'],
]

for (const [input, expected] of cases) {
  test(`${JSON.stringify(input).slice(0, 40)} -> ${expected}`, () => {
    assert.equal(safeRedirect(input), expected)
  })
}
JS
npm test

A few rows are worth a second look. /%2F%2Fevil.example stays as it is, because percent-encoded slashes are part of a path, not a new host, and your app will answer it with a 404. https://help.example.org@evil.example/ puts the trusted name in the username part of the URL, and the real host is evil.example. http:evil.example is a quirk of the URL standard: against an http base it parses as a relative path, which rule 3 never sees, because the value does not start with /.

Check it worked

npm test finds the file in test/ and ends with a summary that shows 21 tests, 21 passing and 0 failing. To see a row fail, change '/' to '/x' on the //evil.example line, run npm test again, and change it back.

Step 5 · Use the check in the sign-in flow

Replace app.js with a version that sends next through safeRedirect in both places: when the form is drawn, and when the redirect is sent. Checking only one of them is a common gap, because the form can be posted by hand without ever loading GET /login.

Bash
cat > app.js <<'JS'
import { createServer } from 'node:http'
import { safeRedirect } from './safe-redirect.js'

const escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)

export function createApp() {
  return createServer(async (req, res) => {
    const url = new URL(req.url, 'http://localhost')

    if (req.method === 'GET' && url.pathname === '/login') {
      const next = safeRedirect(url.searchParams.get('next'))
      res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
      res.end(`<form method="post" action="/login">
  <input name="user" value="amara">
  <input type="hidden" name="next" value="${escapeHtml(next)}">
  <button>Sign in</button>
</form>\n`)
      return
    }

    if (req.method === 'POST' && url.pathname === '/login') {
      let body = ''
      for await (const chunk of req) {
        body += chunk
        if (body.length > 10_000) {
          res.writeHead(413).end()
          return
        }
      }
      const form = new URLSearchParams(body)
      // A real app checks the password here.
      res.writeHead(303, {
        location: safeRedirect(form.get('next')),
        'set-cookie': 'sid=demo-session; HttpOnly; SameSite=Lax; Path=/',
      })
      res.end()
      return
    }

    if (req.method === 'GET' && url.pathname === '/dashboard') {
      res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
      res.end('Dashboard\n')
      return
    }

    res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
    res.end('Not found\n')
  })
}
JS

Add a test that drives the app over HTTP. It listens on port 0, so the system picks a free port, and fetch with redirect: 'manual' returns the 303 response itself instead of following it:

Bash
cat > test/sign-in.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { createApp } from '../app.js'

let server
let base

before(async () => {
  server = createApp()
  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
  base = `http://127.0.0.1:${server.address().port}`
})

after(() => server.close())

async function signIn(next) {
  const res = await fetch(`${base}/login`, {
    method: 'POST',
    body: new URLSearchParams({ user: 'amara', next }),
    redirect: 'manual',
  })
  return { status: res.status, location: res.headers.get('location') }
}

test('a path on this site is kept', async () => {
  assert.deepEqual(await signIn('/orders?id=7'), { status: 303, location: '/orders?id=7' })
})

test('another site falls back to the home page', async () => {
  assert.deepEqual(await signIn('https://evil.example/'), { status: 303, location: '/' })
})

test('the sign-in form only carries a safe value', async () => {
  const html = await (await fetch(`${base}/login?next=//evil.example`)).text()
  assert.match(html, /name="next" value="\/"/)
})
JS
npm test

Start the app again in the second terminal:

Bash
npm start

Then repeat the two requests from step 2, and one with a real path:

Bash
curl -si -X POST --data 'user=amara&next=https://evil.example/' http://127.0.0.1:3000/login | grep -i '^location'
curl -si -X POST --data 'user=amara&next=//evil.example' http://127.0.0.1:3000/login | grep -i '^location'
curl -si -X POST --data 'user=amara&next=/dashboard' http://127.0.0.1:3000/login | grep -i '^location'

Stop the server with Ctrl+C when you are done.

Check it worked

npm test now reports 24 passing tests and 0 failing. The two attack requests print location: /, and the last one prints location: /dashboard. The same check belongs on every other redirect that takes a value from a request: a sign-out ?return= link, the "continue" button after email confirmation, a language switcher that sends you "back" to the page you were on. Search your code for them:

Bash
grep -rnE "location|redirect" --include='*.js' . | grep -v test/ | grep -v node_modules

In this demo, every hit in app.js goes through safeRedirect. In your own project, each hit that uses a query value, a form field or the Referer header without it is a bug to fix. Frameworks have their own redirect helpers, such as res.redirect() in Express, and they do not check the target for you.

Step 6 · Register exact OAuth redirect URIs

"Sign in with Google" and other OAuth and OpenID Connect flows have their own redirect: after the user approves, the provider sends them to your redirect_uri with a one-time code. If the provider accepts any URL that loosely matches, an attacker can have that code delivered to a page they control. The OAuth security best practice (RFC 9700) requires providers to compare redirect URIs by exact string match. Your side of the job is to register them that way.

In your provider's client settings:

  • List each callback as a full URL, for example https://app.your-domain.com/auth/callback. Include the scheme, host and path. Do not use wildcards, such as https://*.your-domain.com/*.
  • Keep a separate entry for each environment you really use (http://localhost:3000/auth/callback for development), and delete old entries when an environment goes away.
  • If your app uses OpenID Connect sign-out, register post_logout_redirect_uri values the same way. The spec requires the provider to check them against the registered list.

Inside your app, do not put the user's next value into the redirect_uri, because that would make your callback URL change with every request. Keep redirect_uri fixed. Store the checked next value on the server next to the state value you already send, and check it again when the callback runs:

JavaScript
// When sign-in starts
const state = crypto.randomUUID()
pendingSignIns.set(state, safeRedirect(req.query.next))
// ...send the user to the provider with this state and the fixed redirect_uri

// In /auth/callback, after the code is exchanged and verified
const next = pendingSignIns.get(req.query.state)
pendingSignIns.delete(req.query.state)
res.redirect(303, safeRedirect(next))

pendingSignIns stands for whatever your app already uses to keep state between the two requests, such as the session store. The second safeRedirect call costs nothing and protects you if that storage is ever filled from somewhere else.

Check it worked

Your provider's settings page lists only full https:// callback URLs (plus any http://localhost entries for development), none with a *, and none for environments you no longer run. In your code, redirect_uri is a constant or a configuration value, never built from request input, and the value you redirect to after the callback passes through safeRedirect.

Next steps

  • See how the OAuth flow, state and PKCE fit together: /tutorials/understand-oauth-2-1-and-openid-connect-with-pkce
  • Stop other sites from posting forms to your app: /tutorials/protect-forms-from-csrf-with-samesite-cookies-and-tokens
  • Apply the same "parse, then compare against a fixed list" thinking to URLs your server fetches: /tutorials/block-server-side-request-forgery-in-a-link-preview-feature
  • Clean up when you are finished: rm -rf ~/redirect-demo

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.