Server-only modules let you run code only on the server, keeping it safe and hidden from users. This helps protect secrets and improve performance.
0
0
Server-only modules in NextJS
Introduction
When you need to keep API keys or database passwords secret.
When you want to run code that should never be sent to the browser.
When fetching data from a database or external service securely.
When performing server-side calculations or processing.
When you want to reduce the amount of code sent to the client.
Syntax
NextJS
import 'server-only'; // Your server-only code here export async function getServerData() { // fetch or process data const data = {}; // example placeholder return data; }
Use import 'server-only'; at the top to mark the module as server-only.
Server-only modules cannot be imported into client components.
Examples
This module safely returns a secret key only on the server.
NextJS
import 'server-only'; export async function getSecret() { return process.env.SECRET_KEY; }
This module fetches data from an API only on the server side.
NextJS
import 'server-only'; export async function fetchData() { const res = await fetch('https://api.example.com/data'); return res.json(); }
Sample Program
This server-only module exports a function that returns the current server time as a string. It runs only on the server, so the time is always accurate and hidden from the client.
NextJS
import 'server-only'; export async function getServerTime() { return new Date().toISOString(); }
OutputSuccess
Important Notes
Server-only modules help keep sensitive data safe by never sending it to the browser.
Trying to import server-only modules into client components will cause errors.
Use server-only modules for backend logic, database calls, and secret management.
Summary
Server-only modules run only on the server and are hidden from the browser.
They protect secrets and improve app security.
Mark them with import 'server-only'; at the top.