Next.js › Security Best Practices in Next.js

Why is it important to never expose sensitive information like API keys inside client components?

Beginner

Answer

Anything included in a client component becomes part of the JavaScript bundle sent to every visitor's browser, meaning anyone can view it by inspecting the page, so secrets like API keys or database credentials must stay in server only code, such as server components, route handlers, or server actions.
// Never do this in a client component
'use client';
const apiKey = 'sk_live_secret_key_12345'; // exposed to everyone

// Instead, use it only in server side code
const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } });
Real-world example A team accidentally included a payment provider's secret key inside a client component, and after realizing anyone could view it in their browser's developer tools, they immediately rotated the key and moved the logic to a server action.

Common follow-ups: How do you check if a secret has accidentally been exposed to the browser?;What is the difference between a public and a secret environment variable?