The URL constructor lets you parse and build URLs cleanly: new URL('https://itsourcecode.com/path') gives you .host, .pathname, .searchParams properties. It is global in modern Node and browsers, but old IE11 and very old Node throw ReferenceError: URL is not defined. Three fixes.

Step 1: Identify environment
| Where | Status |
|---|---|
| Modern browser | URL is global |
| IE11 | No native URL – needs polyfill |
| Node 10+ | URL is global |
| Node 9 or older | require(‘url’).URL |
| React Native old | Needs react-native-url-polyfill |
Fix 1: Modern Node and browser (works out of the box)
const url = new URL('https://itsourcecode.com/free-projects/?lang=php');
console.log(url.host); // 'itsourcecode.com'
console.log(url.pathname); // '/free-projects/'
console.log(url.searchParams.get('lang')); // 'php'
// Mutate parts:
url.searchParams.set('page', '2');
console.log(url.toString());
// 'https://itsourcecode.com/free-projects/?lang=php&page=2'
Fix 2: Old Node (pre-v10)
const { URL } = require('url');
const u = new URL('https://example.com/api');
Fix 3: IE11 polyfill
npm install url-polyfill
import 'url-polyfill';
// Now new URL() works in IE11
const u = new URL('https://example.com');
// Or in HTML script tag (CDN):
<script src="https://cdn.jsdelivr.net/npm/[email protected]/url-polyfill.min.js"></script>
Fix 4: React Native (Hermes / older versions)
npm install react-native-url-polyfill
// In your entry file (App.js or index.js):
import 'react-native-url-polyfill/auto';
URL vs URLSearchParams cheat sheet
// Parse query string:
const params = new URLSearchParams('?a=1&b=2');
params.get('a'); // '1'
params.append('c', '3');
params.toString(); // 'a=1&b=2&c=3'
// Build URL from scratch:
const u = new URL('https://api.example.com');
u.pathname = '/search';
u.searchParams.set('q', 'capstone');
u.toString();
// 'https://api.example.com/search?q=capstone'
Debugging checklist for ReferenceError
Before diving into fixes, run through this diagnostic checklist. Nine times out of ten the answer surfaces here.
- Read the full traceback, not just the error message. The stack trace shows exactly which line and which call chain triggered the error. The last line names the immediate cause; earlier lines show how you got there.
- Add print or debug statements just before the failing line. Print the variable, its type, and its value. Nine out of ten error surprises come from the value being different from what you assumed.
- Check JavaScript / Node.js version compatibility. Errors sometimes result from APIs that changed between versions. Run your interpreter version check and compare against the library documentation for that version.
- Isolate the failing call in a minimal reproducer. Copy the failing line into a small standalone script with hardcoded inputs. If it fails there too, the bug is in your code. If not, something in your surrounding context is contributing.
- Search the exact error message. Include the class name and the specific text in your search. Chances are someone else hit the same issue and the fix is documented on Stack Overflow or the library’s GitHub issues.
Common causes for ReferenceError
Most instances of this error trace back to one of these root causes:
- Uninitialized or missing input. A variable was not populated before use, or the input source (file, API response, database row) did not contain the expected key or value.
- Type mismatch. The code expected a specific type (dict, list, string) but received something different. JavaScript / Node.js’s dynamic typing means this often surfaces at runtime, not at compile time.
- Version drift. The library API changed and your code assumes the old signature. Check the library’s changelog for breaking changes since the version you last used.
- Race condition or ordering issue. Async or concurrent code sometimes tries to access data before it is ready. Add awaits, locks, or explicit ordering to fix.
- Copy-paste from stale tutorial. Older tutorials may use APIs that no longer exist. Always check the official docs for the current version.
Testing and prevention
Preventing this class of error from recurring is more valuable than fixing it once. Build these habits into your workflow:
- Write tests that trigger the error path. If your test suite hits the error scenario, catch and assert it. A well-written test prevents the same bug from returning.
- Validate inputs at API boundaries. When data enters your code from external sources (HTTP requests, file uploads, database queries), validate structure and types immediately.
- Use type hints and static analysis. Tools like mypy for Python or TypeScript for JavaScript catch many type mismatches before you run the code.
- Log important state. Structured logging with context helps you debug production issues faster. Include enough context to reconstruct what happened.
- Read the library changelog. Before upgrading a dependency, skim the changelog for breaking changes. Two minutes of reading saves an hour of debugging.
When to ask for help
Some errors are worth solving yourself for the learning. Others are worth asking about early. Ask for help when: the error blocks a customer-facing feature, you have spent an hour without progress, the error involves security or data integrity, or you are unsure whether your fix will introduce new bugs. Post to Stack Overflow with a minimal reproducer, or ask a senior developer on your team. Time boxes are your friend.
Production hardening for ReferenceError
Fixing ReferenceError once is not enough. To prevent it from recurring in production, harden the surrounding code with these patterns.
- Defensive coding at API boundaries. Every function that receives external data (HTTP requests, database rows, file uploads, third-party API responses) should validate structure and types before proceeding. Use validation libraries like Pydantic (JavaScript specific) to enforce schemas at the boundary.
- Structured logging with context. When ReferenceError occurs, your logs should include enough context to reconstruct the failure. Include the operation name, input values, user or request ID, and the full stack trace. Avoid logging sensitive data (passwords, tokens, PII).
- Error monitoring and alerting. Tools like Sentry, Rollbar, or Datadog capture production errors with stack traces and context. Set up alerts for ReferenceError so you know within minutes when it happens in production.
- Retry logic with exponential backoff. For transient errors (network failures, temporary API errors), retry with 1-second, 2-second, 4-second delays. Cap at 3-5 retries to prevent infinite loops.
- Circuit breakers for external dependencies. If an external service repeatedly fails, stop calling it for a period and return a fallback response. Prevents cascading failures.
Testing strategies to catch ReferenceError early
Investing in tests that specifically trigger the error path prevents regressions. Build these into your test suite:
- Unit tests for the failing function. Write a test that reproduces the exact conditions that caused ReferenceError. If your test fails, your fix works. If your test passes with the buggy code, your test is not testing the right thing.
- Property-based testing. Tools like Hypothesis for Python generate random inputs and check invariants hold. Great for catching edge cases you did not think of.
- Integration tests with real dependencies. Mock-heavy unit tests miss real-world issues. Have at least one integration test that hits a real database, API, or file system.
- Continuous integration. Run your test suite on every pull request. Catch bugs before they reach main.
Frequently Asked Questions
Should I still polyfill URL for IE11 in 2026?
Only if your project still claims IE11 support, which is extremely rare in 2026 (Microsoft retired IE in 2022). Most analytics show under 0.1% IE11 traffic globally. Drop IE11 support if you can; otherwise yes, url-polyfill works.
URL vs URLSearchParams: when to use each?
URL is for full URLs (protocol, host, path, query, hash). URLSearchParams is just the query-string piece. Use URL when you start from a complete URL string; use URLSearchParams when you only need to manipulate query params and already have the URL elsewhere.
Why does new URL(‘hello’) throw?
URL requires an absolute URL (with scheme). For relative URLs, pass a base: new URL(‘hello’, ‘https://itsourcecode.com’). The result is ‘https://itsourcecode.com/hello’.
Can I use URL to validate a string?
Yes, wrap in try/catch: try { new URL(input) } catch { return false }. Note that this accepts ftp://, mailto:, javascript: etc., so add a protocol check if you only want http/https.
How do I round-trip query params with arrays?
URLSearchParams supports repeated keys: params.append(‘tag’, ‘php’); params.append(‘tag’, ‘mysql’). params.getAll(‘tag’) returns [‘php’, ‘mysql’]. params.toString() gives ‘tag=php&tag=mysql’.
