Prevent API Key Leaks in Next.js: Secure SDK InitializationPrevent API Key Leaks in Next.js: Secure SDK Initialization
The network for creativity
Join 1.25M professional creatives like you
Connect with clients, get discovered, and run your business 100% commission-free
Creatives on Contra have earned over $150M and we are just getting started
How a Single Line of Code Can Break Your Next.js App Router Build (and leak your API keys) šŸ›‘
I recently ran into a classic TimeoutError and Missing API key crash during local development in a Next.js project using Resend for transactional emails.
The culprit? A single line placed at the root of a server action file: āŒ const resend = new Resend(process.env.RESEND_API_KEY);
šŸ” What was happening under the hood? Even if you use "use server"; at the top of your file, initializing a third-party SDK directly at the file's root level can cause major headaches:
Client-Side Import Triggers: If any component or type (like an enum or status type) from that file is accidentally imported into a Client Component, the browser tries to evaluate the entire file.
The Environment Variable Leak: Since process.env keys are protected and not exposed to the browser by default, the constructor receives undefined, causing the application to crash instantly on the client side with a Missing API key error.
Static Generation Failures: It forces static routes to bail out or timeout during compilation because it tries to evaluate dynamic server-side logic outside of an actual server lifecycle.
šŸ’” The Fix The solution is a fundamental best practice for Next.js App Router: Keep your SDK initialization localized inside the scope of the server function itself, rather than globally at the top of the file.
TypeScript "use server"; import { Resend } from "resend";
export async function sendOrderConfirmationEmail(orderEmail: string) { // āœ… Instantiate only when the server function runs const resend = new Resend(process.env.RESEND_API_KEY);
try { return await resend.emails.send({ ... }); } catch (error) { console.error("Email sending failed:", error); } } Takeaway: Never let your SDK constructors hang around in the global scope of your modules. Wrap them tightly inside your actions to keep your bundle clean, your API keys safe, and your Next.js build blazing fast! ⚔
#NextJS #WebDevelopment #FullStack #React #JavaScript #CodingTips #WebSecurity #Resend
Back to feed
The network for creativity
Join 1.25M professional creatives like you
Connect with clients, get discovered, and run your business 100% commission-free
Creatives on Contra have earned over $150M and we are just getting started