0
0
NextjsConceptBeginner · 3 min read

What is Server Only in Next.js: Explanation and Example

Server only in Next.js means code that runs exclusively on the server and never reaches the browser. It is used to keep sensitive logic or data safe and improve performance by avoiding client-side execution.
⚙️

How It Works

In Next.js, some code can be marked as server only, which means it runs only on the server side during rendering or API calls. Imagine a kitchen where the chef prepares food (server) and the waiter serves it to customers (browser). The chef's work is hidden from customers, just like server-only code is hidden from users.

This separation helps keep secrets like database passwords or API keys safe because they never leave the server. Also, it reduces the amount of code sent to the browser, making pages load faster and run smoother.

💻

Example

This example shows a Next.js API route that runs only on the server. It fetches secret data and sends it to the client safely.

typescript
import { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  // This code runs only on the server
  const secretData = process.env.SECRET_API_KEY || 'default_secret';
  res.status(200).json({ secret: secretData });
}
Output
{"secret":"your_secret_api_key_here"}
🎯

When to Use

Use server only code when you need to protect sensitive information like API keys, database credentials, or private business logic. It is also useful for tasks that require secure environment variables or heavy computation that should not slow down the browser.

Real-world cases include fetching data from a private database, handling payments, or processing user authentication securely.

Key Points

  • Server only code runs exclusively on the server, never in the browser.
  • It protects sensitive data and improves performance.
  • Commonly used in API routes, server components, and getServerSideProps.
  • Helps keep environment variables and secrets safe.

Key Takeaways

Server only code in Next.js runs exclusively on the server, never reaching the browser.
Use server only code to keep secrets like API keys and database credentials safe.
Server only code improves performance by reducing client-side load.
API routes and server components are common places for server only code.
Avoid exposing sensitive logic or data in client-side code.