getBaseURL
Returns the base URL of the current location. Includes protocol, hostname, and port if present.
1/**
2 * Returns the base URL of the current location.
3 * Includes protocol, hostname, and port if present.
4 *
5 * @returns The base URL string (e.g., "https://example.com:3000").
6 */
7export function getBaseURL(): string {
8 if (typeof window === 'undefined' || !window.location) return '';
9 const { protocol, hostname, port } = window.location;
10 return `${protocol}//${hostname}${port ? `:${port}` : ''}`;
11}
Environment-Safe Fallback
Gracefully handles non-browser environments (e.g., SSR or Node) by returning an empty string when
window
is unavailable.Complete and Precise Output
Includes protocol, hostname, and port (when applicable), ensuring a fully qualified base URL.
Zero Dependencies
Relies solely on the built-in
window.location
object, avoiding external libraries or complex parsing.Consistent Behavior Across Browsers
Uses standard DOM APIs for location parsing, which are uniformly supported across major browsers.
Tests | Examples
1const originalLocation = window.location;
2
3function mockLocation(href: string) {
4 delete (window as any).location;
5 (window as any).location = new URL(href);
6}
7
8afterEach(() => {
9 window.location = originalLocation;
10});
11
12test('getBaseURL - returns full origin with port', () => {
13 mockLocation('https://example.com:8080/some/path');
14 expect(getBaseURL()).toBe('https://example.com:8080');
15});
16
17test('getBaseURL - returns origin without port if default', () => {
18 mockLocation('https://example.com/path');
19 expect(getBaseURL()).toBe('https://example.com');
20});
21
22test('getBaseURL - works with http', () => {
23 mockLocation('http://localhost:3000/test');
24 expect(getBaseURL()).toBe('http://localhost:3000');
25});
26
27test('getBaseURL - returns empty string in non-browser environment', () => {
28 const origWindow = global.window;
29 delete (global as any).window;
30 expect(getBaseURL()).toBe('');
31 global.window = origWindow;
32});
Common Use Cases
Constructing Absolute URLs
Build full resource URLs by appending paths or query strings to the base URL.
API Endpoint Prefixing
Dynamically derive API roots or CDN prefixes based on the current origin.
Client-Side Logging or Analytics
Capture and store base domain information for debugging or telemetry purposes.
SSR/CSR Compatibility Checks
Determine runtime environment and fall back safely in isomorphic JavaScript applications.