4οΈβ£ The TL;DR π
Browsers are smart enough to fill in the blanks for URLs. Servers aren't.
Always use an absolute URL built with an environment variable when fetching data inside a Next.js Server Component. π
#NextJS#WebDevelopment#100DaysOfCode
Next.js Server Components are incredible, but they come with one annoying quirk that catches everyone off guard. β οΈ
If you try to fetch('/api/data') inside a Server Component, your app will crash.
Here is why, and how to fix it instantly. π§΅π
3οΈβ£ The Production Fix π
You don't want to hardcode localhost:3000, because it will break when you deploy to Vercel!
The fix?
Use a dynamic environment variable:
const baseUrl = https://t.co/6ypRxz6Dgo_PUBLIC_BASE_URL;
await fetch(baseUrl + '/api/events');
Storing raw image files directly in your MongoDB database is a massive rookie mistake. π
It bloats your DB, slows down queries, and costs a fortune.
Here is the production-ready way to handle Image Uploads in a Next.js 16 API Route. π§΅π
4οΈβ£ The TL;DR π
Client sends FormData.
Next.js API turns the File into a Buffer.
Cloudinary stores the Buffer and returns a URL.
MongoDB stores the URL string.
Insanely fast, infinitely scalable. π
#NextJS#JavaScript#Backend
3οΈβ£ The TL;DR π
Need it for a database or secure API? Use SECRET_KEY. (Server Only)
Need it for a UI component or frontend tracking? Use NEXT_PUBLIC_KEY. (Client & Server)
Simple prefix. Massive security implications. π
#NextJS#WebDev#ReactJS
Next.js environment variables confused the heck out of me until today. π€―
If you are leaking API keys to the browser, or getting "undefined" errors on the client side, you are probably making this one simple mistake.
Here is the ultimate Next.js .env cheat sheet. π§΅π
2οΈβ£ The NEXT_PUBLIC_ Magic Key π
What if you actually need a variable on the frontend? (Like a public URL or a PostHog tracking key?)
Just add NEXT_PUBLIC_ to the front of the variable name! Ex: NEXT_PUBLIC_BASE_URL=http://localhost:3000