URL.resolve
- Node.js course
- Intermediate
- Lesson 109/116
- 5 min
Learn to resolve relative URLs with URL.resolve.
Resolving relative URLs
When a page has a relative link like "/sub", the browser turns it into a full address. This is called URL resolution. In Node.js you do it with new URL(relative, base).
Example: new URL("sub", "https://example.com/main") gives https://example.com/sub. new URL("../sibling", "https://example.com/a/b/c") gives https://example.com/a/sibling. base is the second parameter; the relative path is resolved against it. Older Node.js versions had a url.resolve(base, relative) function; it has been removed. In new code always use new URL(relative, base). This is useful for crawling relative links on a page or building endpoints from an API base.
Base and relative interaction
The result of resolution comes from the relative path replacing the last path component of the base. "./" means the same directory, "../" the parent, "/" the root.
Examples: new URL("./x", "https://example.com/a/b") → https://example.com/a/x; new URL("../x", "https://example.com/a/b") → https://example.com/x; new URL("/x", "https://example.com/a/b") → https://example.com/x. If the relative path contains a protocol like https://, the base is ignored; the absolute URL is used directly. This matches the <a href> logic in browsers. Resolving all links of a site from a single base keeps behavior consistent.
Practice Resolve a relative URL
Define const base = "https://example.com/ana/sayfa";. Resolve with const resolved = new URL("alt", base);. Print with console.log(resolved.href).
Starter code
// Define the base address
// write here
// Resolve the relative path
// write here
// Print the result
// write hereSample solution
const base = "https://example.com/ana/sayfa";
const resolved = new URL("alt", base);
console.log(resolved.href);Expected output
https://example.com/ana/alt
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the modern way to resolve a relative URL?
new URL("alt", "https://example.com/ana")- new URL(relative, base) Correct answer
- url.resolve(base, rel)
- url.parse(rel)
- path.join(base, rel)
Explanation: new URL(relative, base) is the modern and recommended way.
2 Match each relative path to its meaning
| Term | Meaning |
|---|---|
./x |
Same directory |
../x |
Parent directory |
/x |
Root directory |
https://... |
Absolute (base ignored) |
3 Complete the resolution call
const resolved = new URL(____, base);
const resolved = new URL("alt", base);
Explanation: The relative path "alt" is resolved against the base.