Fixing the Wildcard CORS ↩️ Error in a NestJS App on a Shared VPS: Why “Access‑Control‑Allow‑Origin: *” Keeps Failing and How I Cracked It in 30 Minutes
Imagine you’ve just pushed a brand‑new NestJS API to a cheap shared VPS, slapped a * on Access-Control-Allow-Origin, refreshed your React front‑end, and—boom—“CORS header ‘Access‑Control‑Allow‑Origin’ missing” pops up in the console. You’re sweating, the deadline is looming, and the error feels like a brick wall.
This article walks you through the exact reason the wildcard header won’t work on a shared VPS, and shows you a 30‑minute, copy‑and‑paste solution that gets your API talking to any client again.
Why This Matters
Cross‑origin requests are the lifeblood of modern JavaScript apps. If your API refuses to serve the correct CORS headers, every fetch, Axios call, or GraphQL query crashes before it even reaches your business logic. In a production environment the fallout is immediate:
- Lost customers because the UI never loads.
- Higher support tickets and wasted dev time.
- Potential revenue loss if the API powers a checkout flow.
Fixing it fast isn’t just a convenience—it’s a revenue‑protecting move.
Step‑by‑Step Tutorial
-
Confirm the Real Error
Open Chrome DevTools → Network, click the failing request, and look at the Response Headers. If you see
Access-Control-Allow-Origin: *but the browser still complains, the problem is *not* the header itself. -
Check Your VPS Proxy Settings
Most shared hosts sit behind a reverse proxy (NGINX, Apache, or a custom load balancer). These proxies often strip or overwrite response headers for security reasons.
Tip: Run
curl -I https://yourdomain.com/api/healthfrom a different machine. If theAccess-Control-Allow-Originheader is missing, the proxy is the culprit. -
Add CORS Middleware Directly in NestJS
Open
main.tsand enable the built‑in CORS options. The wildcard works *only* whenoriginis explicitly set totrueandcredentialsis false.import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule, { cors: { origin: true, // <-- lets any origin pass methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', allowedHeaders: 'Content-Type, Authorization', credentials: false // <-- must be false for wildcard }}); await app.listen(3000); } bootstrap(); -
Force the Header Through the Proxy
If your host uses NGINX, add a snippet to the site’s
nginx.conf(or ask support to insert it). This tells the proxy to keep the CORS header.location / { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; # ---- CORS fix start ---- add_header Access-Control-Allow-Origin * always; add_header Access-Control-Allow-Methods 'GET,POST,PUT,DELETE,OPTIONS' always; add_header Access-Control-Allow-Headers 'Authorization,Content-Type' always; # ---- CORS fix end ---- }Warning: Never set
Access-Control-Allow-Credentials: truewith a wildcard. Browsers will reject it. -
Reload the Proxy & Verify
On most shared VPS panels you can restart the web service with a single button. After restart, run the
curlcommand again. You should now see the header present.Finally, hit your front‑end again. The CORS error should be gone, and your API will respond with data.
Real‑World Use Case: SaaS Dashboard on a Budget VPS
Our client runs a subscription‑based analytics dashboard. The back‑end is a NestJS microservice, the front‑end is a Next.js app hosted on Vercel. The VPS costs $5/month, so we can’t afford a dedicated load balancer.
After deploying the app, the dashboard kept throwing “CORS header missing” even though app.enableCors({ origin: '*'}); was in place. By applying the proxy add_header fix, we restored cross‑origin functionality in under half an hour, saved $200 in consulting fees, and kept the monthly host bill under $10.
Results / Outcome
- Time to fix: ~30 minutes (including testing)
- Performance impact: none—CORS headers are tiny and added at the proxy level.
- Security: unchanged because we kept
credentials: falseand only exposed read‑only endpoints. - Bottom line: API reachable from any domain, zero downtime, and the client can now launch new features without a CORS roadblock.
Bonus Tips
- If you need to support credentials, replace the wildcard with an explicit domain list and set
credentials: true. - Use
helmetin NestJS to add other security headers while you’re tweaking CORS. - Automate the proxy update with a simple
scpscript so you can push header changes from your CI pipeline. - Monitor CORS responses with a lightweight health check endpoint that returns the current header values.
Pro tip for freelancers: Offer a “CORS audit” as a $49 add‑on. It’s a quick win that many clients overlook, and it can easily turn a $0‑hour fix into a paid service.
Monetization Corner (Optional)
If you run a dev blog or YouTube channel, embed an affiliate link to a VPS provider that offers a free trial. Readers who fix their CORS error will likely need a reliable host, and you earn a commission for every signup.
Or bundle this tutorial into a “Rapid API Deployment” e‑book and sell it on Gumroad. The content alone can fetch $5‑$10 per download, and the upside is pure passive income.
No comments:
Post a Comment