Next.js - use server Directive



The "use server" Directive

The "use server" is a Next.js directive used to specify that a component should be rendered on the server-side. Server side components are run on the server-side and are bundled with the server-side code while application build. You can make server side component for:

  • Component that include database queries
  • Component that include API calls
  • Component that include business logic

Define a Server Component

To define a server component, create a file with the .js/.jsx/.tsx extension and add the "use server" directive at the top of the component file. This declaration will make all the function defined inside the component to be executed on the server-side.

// /actions/fetchUsers.js

'use server'
import { db } from '@/lib/db' // Your database client
 
export async function createUser(data: { name: string; email: string }) {
    const user = await db.user.create({ data })
    return user
}

Using Server Functions in a Client Component

To use Server Functions in Client Components you need to create your Server Functions in a dedicated file using the use server directive at the top of the file. These Server Functions can then be imported into Client and Server Components and executed.

In the code below, we imported the server component that we created above and used it inside the client component.

'use client'
import { fetchUsers } from '../actions'
    
export default function MyButton() {
    return <button onClick={() => fetchUsers()}>
             Fetch Users
           </button>
}
Advertisements