Validate navigation destinations with parsed URLs
Quick answer
A syntactically valid URL is not necessarily an allowed destination. Parse it with URL, compare the normalized protocol and origin, and apply the application’s path policy before creating navigation.
How it works
For a same-origin return destination, use a fixed application base, require HTTPS, exact origin equality, no credentials, and allow only known pathnames. Return a canonical absolute URL or reject. Path matching here is a narrow policy, not a general redirect sanitizer. A backend must also check redirects and authorization on its own; a permitted URL can still lead to content that requires permission.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {function safe(s){try{const u=new URL(s,"https://shop.example/");return u.origin==="https://shop.example"&&u.protocol==="https:"&&!u.username&&!u.password&&["/catalog","/account"].includes(u.pathname)?u.href:null;}catch{return null;}}console.log(safe("/catalog"),safe("https://other.example/catalog"));})()Expected console output:
https://shop.example/catalog nullThe relative allowed route resolves canonically; the unrelated origin is rejected.
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const u=new URL("https://SHOP.example:443/account");console.log(u.origin,u.pathname,u.origin==="https://shop.example");})()Expected console output:
https://shop.example /account trueThe URL parser normalizes the host and default port.
Common mistakes
Do not use a substring test for host identity or accept arbitrary schemes because parsing succeeded.
Practice
Allow only /catalog and /account on a fixed HTTPS origin. Test a relative path, an unrelated host and an unlisted pathname.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Validate navigation destinations with parsed URLs — Knowledge Check
Apply the concept and reason about local example output.
What is the correct comparison for an allowed navigation origin?
Why reject unknown paths even on the intended origin in this exercise?
What does parsing a URL establish?
What is the exact console output in Validate navigation destinations with parsed URLs example 1?
(async () => {function safe(s){try{const u=new URL(s,"https://shop.example/");return u.origin==="https://shop.example"&&u.protocol==="https:"&&!u.username&&!u.password&&["/catalog","/account"].includes(u.pathname)?u.href:null;}catch{return null;}}console.log(safe("/catalog"),safe("https://other.example/catalog"));})()What is the exact console output in Validate navigation destinations with parsed URLs example 2?
(async () => {const u=new URL("https://SHOP.example:443/account");console.log(u.origin,u.pathname,u.origin==="https://shop.example");})()