URL Base Resolves Relative References
new URL resolves relative references against a base: plain segments replace the tail, .. climbs, and a leading slash restarts from the root.
Code
// A base URL makes relative references resolvable
const base = 'file:///srv/app/public/';
// Plain segments replace the last path segment of the base
console.log(new URL('logs/app.txt', base));
// '..' climbs and '.' stays — both normalized
console.log(new URL('logs/../assets/logo.svg', base));
console.log(new URL('./index.html', base));
// A leading slash replaces the whole path from the root
console.log(new URL('/health', base));
// Without a base, a relative reference throws
try {
new URL('logs/app.txt');
} catch (err) {
console.log('no base:', err instanceof TypeError);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
URL {
href: 'file:///srv/app/public/logs/app.txt',
origin: 'null',
protocol: 'file:',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '/srv/app/public/logs/app.txt',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
URL {
href: 'file:///srv/app/public/assets/logo.svg',
origin: 'null',
protocol: 'file:',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '/srv/app/public/assets/logo.svg',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
URL {
href: 'file:///srv/app/public/index.html',
origin: 'null',
protocol: 'file:',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '/srv/app/public/index.html',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
URL {
href: 'file:///health',
origin: 'null',
protocol: 'file:',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '/health',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
no base: trueInside the snippet
Demo state sits in top-level bindings: base.
Points of care
- The package manager never enters the picture for this snippet.
Putting it to use
The demo output is labeled (no base:), so every printed line maps back to its originating operation.
Core lines under the microscope
const base = 'file:///srv/app/public/';
new URL('logs/app.txt');
Interactive Tools for This Topic
Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Nano ID GeneratorGenerate URL-safe Nano ID strings with a configurable length and alphabet using the Web Crypto API.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `base`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.