The use server directive tells Next.js that a function runs only on the server. This helps keep your app secure and fast by separating server code from client code.
0
0
Use server directive in NextJS
Introduction
When you want to write a function that fetches data securely on the server.
When you need to handle sensitive operations like database updates or authentication.
When you want to keep your client bundle small by not sending server-only code to the browser.
When you want to use server-only APIs or environment variables safely.
When you want to create server actions that can be called from client components.
Syntax
NextJS
"use server"; export async function myServerFunction() { // server-only code here }
The directive "use server"; must be the very first line in the file or function.
Functions marked with use server can be imported and called from client components as Server Actions.
Examples
This function fetches user data only on the server.
NextJS
"use server"; export async function fetchUserData() { const res = await fetch('https://api.example.com/user'); return res.json(); }
This function runs only on the server to update the database safely.
NextJS
"use server"; export function updateDatabase() { // code to update database }
Sample Program
This example shows a server function getServerTime that returns the current time as a string. The client component calls this server function when the button is clicked and shows the time.
NextJS
"use server"; export async function getServerTime() { return new Date().toISOString(); } // In a client component 'use client'; import { useState } from 'react'; import { getServerTime } from './serverFunctions'; export default function ShowServerTime() { const [time, setTime] = useState(''); async function fetchTime() { const serverTime = await getServerTime(); setTime(serverTime); } return ( <div> <button onClick={fetchTime} aria-label="Get server time">Get Server Time</button> {time && <p>Server time is: {time}</p>} </div> ); }
OutputSuccess
Important Notes
Remember to keep use server functions free of client-only code like DOM access.
Server functions can be called from client components using Next.js server actions or API routes.
Summary
use server marks functions to run only on the server.
It helps keep sensitive code secure and improves app performance.
Use it when you want to separate server logic from client logic clearly.