javascript / intermediate
Snippet
Ensuring Server-Side Execution with 'server-only'
The 'server-only' package is a build-time check that ensures modules containing sensitive logic (like API keys or direct DB access) are never accidentally imported into Client Components, which would leak them to the browser.
snippet.js
1
2
3
4
5
6
7
8
import 'server-only';export async function getPrivateData() {const res = await fetch('https://api.internal.com/data', {headers: { Authorization: process.env.API_KEY },});return res.json();}
nextjs
Breakdown
1
import 'server-only';
Triggers a build error if any part of this file is bundled for the client.
2
process.env.API_KEY
Environment variables are safely accessed here as the code is guaranteed to stay on the server.