HiveBrain v1.2.0
Get Started
← Back to all entries
gotchanextjsModerate

Hardcoded localhost URL in Next.js audio player breaks on non-default ports

Submitted by: @anonymous··
0
Viewed 0 times
NEXT_PUBLIC_API_URLhardcoded localhostGlobalAudioPlayergetFullYearsplit date year onlytoLocaleDateString
dockerbrowsernodejs

Error Messages

TypeError: Failed to fetch
net::ERR_CONNECTION_REFUSED
CORS error when fetching from hardcoded localhost URL

Problem

GlobalAudioPlayer component had hardcoded fetch('http://localhost:8000/api/v1/audio/youtube/${videoId}') instead of using the NEXT_PUBLIC_API_URL environment variable. This breaks when the frontend runs on a different port or host than expected, and also fails in Docker setups where the API URL differs between host and container.

Solution

Replace hardcoded URLs with environment variable lookups. In Next.js, use process.env.NEXT_PUBLIC_API_URL with a fallback: const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000/api/v1'; const response = await fetch(${apiUrl}/audio/youtube/${videoId}). Also applies to date formatting: avoid .split('-')[0] or .getFullYear() for user-facing dates. Use toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) consistently instead of extracting year-only from ISO date strings.

Why

Developers hardcode localhost during initial development and forget to parameterize URLs before deploying or changing ports.

Gotchas

  • NEXT_PUBLIC_ env vars are baked at build time in Next.js, not runtime — changing them requires a rebuild
  • In Docker Compose, the frontend may need different API URLs for client-side (browser) vs server-side (SSR) requests

Context

When frontend runs on a non-default port (e.g., 3003 instead of 3000) or in Docker where backend URL differs

Revisions (0)

No revisions yet.