The ?next= Bug: Open Redirects in AI-Generated Login Flows
A link on your real domain that ends on someone else's page. How it gets into AI-generated auth code, and the small helper that closes it.
Ask an AI coding assistant to “send users back to the page they were on after they log in” and you will usually get exactly that. A ?next= (or ?redirect=, ?returnTo=, callbackUrl) parameter gets read from the URL and handed to whatever performs the redirect.
The feature works. It is also an open redirect (CWE-601): anyone can build a link that starts on your real domain and ends wherever they like. That includes a pixel-perfect copy of your login page on a domain they control.
It's one of the oldest bugs on the web, and login and logout flows are where it turns up most, because that's where “remember where to go next” logic lives. Here's what it looks like, how it gets abused, and how to fix it properly. The fix needs more than a startsWith("/") check.
The Bug
Here's a typical Express login and logout handler, the kind an assistant writes when asked to “redirect back after login”:
// routes/auth.js
app.post("/login", async (req, res) => {
const user = await verifyCredentials(req.body.email, req.body.password);
if (!user) return res.status(401).render("login", { error: "Invalid login" });
req.session.userId = user.id;
res.redirect(req.query.next || "/dashboard");
});
app.get("/logout", (req, res) => {
req.session.destroy(() => {
res.redirect(req.query.returnTo || "/");
});
});And the same idea on the client, in a Next.js App Router login page:
// app/login/page.tsx
"use client";
import { useSearchParams } from "next/navigation";
export default function LoginPage() {
const searchParams = useSearchParams();
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const res = await fetch("/api/login", {
method: "POST",
body: new FormData(e.currentTarget),
});
if (res.ok) {
window.location.href = searchParams.get("redirect") ?? "/dashboard";
}
}
return <form onSubmit={onSubmit}>{/* email + password fields */}</form>;
}Both pass every test you would think to write. Click a protected page while signed out, get bounced to /login?next=/settings, sign in, land on /settings. The problem is that nothing checks where next points. The value comes from the URL, and anyone can write the URL.
How the Attack Works
The attacker doesn't need access to your server. They just need to send a link:
https://app.example.com/login?next=https://app-example.evil.example/login # or, after a logout: https://app.example.com/logout?returnTo=//evil.example/session-expired
- The victim gets the link in an email or a chat message. The domain is yours, so it looks legitimate.
- They land on your real login page and sign in with their real credentials. Everything up to this point is genuine.
- Your app redirects them to the attacker's page, which looks like your login screen and says “your session expired, please sign in again.”
- They just typed their password into your site a second ago, so typing it again doesn't feel strange. The second copy goes to the attacker.
The logout variant is even quieter. Users expect to land on a login screen after signing out, so a fake one doesn't raise any flags.
In OAuth-style flows it can get worse. If the redirect target is ever built from an authorization response, like a callback that forwards to next with a code or token in the query string or fragment, an open redirect can deliver that credential straight to the attacker's server. OAuth providers have you register redirect URIs for exactly this reason, but an open redirect inside your registered callback route can undo that protection.
Why “Just Check It Starts With /” Isn't Enough
The usual first fix is if (next.startsWith("/")). It blocks https://evil.example, but browsers accept more ways of writing a URL than that check covers:
//evil.exampleis a protocol-relative URL. It starts with/, and the browser takes you toevil.example./\evil.example: browsers treat a backslash like a forward slash in http(s) URLs, so this is the same trick.- Tabs and newlines inside a URL are stripped before parsing, so
/<tab>/evil.examplebecomes//evil.example. javascript:URLs don't start with/, but if your check is a denylist ofhttpandhttps, they get through. Assigned towindow.location, that's script execution, not just a redirect.
There's also a trap in a pattern common in Next.js auth callbacks, where the code prepends the origin to “make it safe”:
// app/auth/callback/route.ts
const { searchParams, origin } = new URL(request.url);
const next = searchParams.get("next") ?? "/dashboard";
return NextResponse.redirect(`${origin}${next}`);
// ?next=@evil.example -> https://app.example.com@evil.example
// The part before "@" is read as a username. The host is evil.example.String-gluing a URL together and hoping it stays on your host doesn't work. Parse it, then check it.
The Fix: Only Accept Same-Site Paths
For login and logout redirects you almost never need to send anyone off-site. So don't allow it: accept only a relative path on your own origin and fall back to a safe default for everything else. One small helper does it:
// lib/safe-redirect.ts
const BASE = "http://localhost.invalid";
export function safeNextPath(raw: unknown, fallback = "/dashboard"): string {
if (typeof raw !== "string" || raw === "") return fallback;
// A same-site path starts with exactly one "/".
// "//evil.example" and "/\evil.example" are protocol-relative URLs
// that browsers resolve to another host.
if (!raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) {
return fallback;
}
// Let the URL parser have the final word: tabs, newlines and other
// tricks are normalized here exactly the way a browser would.
let url: URL;
try {
url = new URL(raw, BASE);
} catch {
return fallback;
}
if (url.origin !== BASE) return fallback;
return url.pathname + url.search + url.hash;
}What this does:
- Rejects anything that isn't a string: missing params, arrays from
?next=a&next=b, and form fields that turned out to be files. - Requires exactly one leading slash. That rules out absolute URLs, schemes like
javascript:, bare hostnames, and the//and/\protocol-relative forms. - Parses with the real URL parser against a placeholder origin and confirms the result stayed on that origin. That catches the whitespace and encoding tricks without you having to list them.
- Returns the normalized path, not the raw input, so what you redirect to is exactly what you checked.
Here's what it returns for the inputs above:
safeNextPath("/settings") // "/settings"
safeNextPath("/billing?tab=plan#top") // "/billing?tab=plan#top"
safeNextPath("https://evil.example") // "/dashboard"
safeNextPath("//evil.example") // "/dashboard"
safeNextPath("/\\evil.example") // "/dashboard"
safeNextPath("/\t/evil.example") // "/dashboard"
safeNextPath("javascript:alert(1)") // "/dashboard"
safeNextPath("@evil.example") // "/dashboard"
safeNextPath(null) // "/dashboard"Then route every redirect through it. On the server:
// routes/auth.js
import { safeNextPath } from "../lib/safe-redirect.js";
app.post("/login", async (req, res) => {
const user = await verifyCredentials(req.body.email, req.body.password);
if (!user) return res.status(401).render("login", { error: "Invalid login" });
req.session.userId = user.id;
res.redirect(safeNextPath(req.query.next, "/dashboard"));
});
app.get("/logout", (req, res) => {
req.session.destroy(() => {
res.redirect(safeNextPath(req.query.returnTo, "/"));
});
});And on the client:
// app/login/page.tsx
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { safeNextPath } from "@/lib/safe-redirect";
export default function LoginPage() {
const router = useRouter();
const searchParams = useSearchParams();
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const res = await fetch("/api/login", {
method: "POST",
body: new FormData(e.currentTarget),
});
if (res.ok) {
router.replace(safeNextPath(searchParams.get("redirect")));
}
}
return <form onSubmit={onSubmit}>{/* email + password fields */}</form>;
}The same helper goes in front of Next.js redirect() in a server action, NextResponse.redirect() in a route handler (as new URL(safeNextPath(next), request.url), not string concatenation), and any router.push() that takes a value from the URL.
If you really do need to send users off-site
Sometimes the destination genuinely is another site you own, like a docs subdomain or a billing portal. Then use an explicit allow-list of hosts, compared exactly:
// Only when you genuinely need to send users to another site you own.
const ALLOWED_HOSTS = new Set(["docs.example.com", "billing.example.com"]);
export function safeExternalUrl(raw: unknown, fallback = "/"): string {
if (typeof raw !== "string") return fallback;
let url: URL;
try {
url = new URL(raw);
} catch {
return fallback;
}
if (url.protocol !== "https:") return fallback;
if (!ALLOWED_HOSTS.has(url.hostname)) return fallback; // exact match only
return url.toString();
}Don't replace that exact match with endsWith("example.com") or includes("example.com"). Both of those accept example.com.evil.example or notexample.com.
Why AI Coding Tools Generate This
“Redirect back to where the user was” is a usability feature, and the shortest code that implements it is the vulnerable version. Tutorials and quick-start examples usually show the parameter going straight into the redirect, because validation makes the snippet longer and it isn't what the example is about.
Nothing tells you it's wrong, either. The happy path behaves perfectly, no test you'd naturally write fails, and no error shows up in your logs. The only person who sends a hostile next value is the attacker.
A Practical Checklist
Start by finding every place a redirect target comes from the request:
grep -rnE "next|redirect|returnTo|return_to|callbackUrl|continue" \ --include=*.ts --include=*.tsx --include=*.js --include=*.jsx --exclude-dir=node_modules . \ | grep -E "redirect\(|router\.(push|replace)|location"
Then, for each hit:
- Login, logout, signup, and invite-accept handlers that read
next,redirect,returnTo,callbackUrl, orcontinuego through one shared helper. Don't write ad-hoc checks per route. - The helper accepts only single-slash relative paths and rejects
//,/\, absolute URLs, and any scheme. - It parses with
new URL()and compares origins. It never relies on string prefix checks alone. - It falls back to a fixed default on anything invalid. Don't show an error that echoes the URL back.
- No URLs are built by concatenation, as in
`${origin}${next}`. Usenew URL(path, base). - Off-site redirects, if any, use an exact host allow-list and require
https:. - OAuth and magic-link callbacks never forward codes or tokens to a URL taken from the request.
- The redirect target is validated where it's used, not just where it's first read. A value stored in a cookie or session before sign-in is still user input when you read it back.
What XploitScan Checks For
Our VC016 Unvalidated Redirect rule flags two shapes of this bug: a dynamic value assigned to window.location / window.location.href or passed to location.assign() / location.replace(), and an Express-style res.redirect() called directly with request input such as req.query.next. Both vulnerable snippets at the top of this post trigger it. Hardcoded destinations like window.location.href = "/dashboard" don't.
Framework-specific sinks like Next.js redirect(), NextResponse.redirect(), and router.push() are where the grep and checklist above earn their keep. Run through them by hand for every auth route.
Scan your repo for this, free
Paste your login handler or upload a file. VC016 is one of the free core rules. No signup.
Scan Your Code — Free