"use client", "use server", and "server-only" in Next.js with Code Examples

"use client", "use server", and "server-only" in Next.js with Code Examples

In Next.js, understanding the differences between "use client", "use server", and "server-only" is key to properly utilizing client and server functionality. These directives and concepts are crucial for defining where and how code should execute in your Next.js application, ensuring both performance and security.

In this blog, we’ll dive deep into each of these concepts, supported by clear code examples to show their practical use.


Client-Server Execution Flow in Next.js


1.use client

The "use client" directive in Next.js tells the framework that the component will be rendered entirely in the browser. This is essential when you need to access browser-specific features like useState, useEffect, or when handling user interactions like click events. All logic inside "use client" will execute in the browser.


Key Points of "use client"

  • Runs only in the browser.
  • Useful for handling user interactions and dynamic updates.
  • Does not have access to server-side functionality.


"use client";
import { getData } from "@/components/actions";
import { getData2 } from "@/components/actions2";
import React from "react";

const Page = () => {
  return (
    <>
      <div>Use Client Component</div>
      <button onClick={() => console.log("Use Client Button Clicked")}>
        Use Client Button
      </button>

      <div>Use Server Component</div>
      <button
        onClick={async () => {
          await getData(); // This will trigger a server-side action
        }}
      >
        Use Server Button
      </button>

      <div>Server Only Component</div>
      <button
        onClick={async () => {
          await getData2(); // This triggers a server-only action
        }}
      >
        Use Server-Only Button
      </button>
    </>
  );
};

export default Page;
        

In this example, the first part is rendered using "use client". It can handle events and update the DOM in the browser. The button inside the "use client" component triggers a client-side action.


2.use server

The "use server" is not the opposite of "use client", but rather an abstraction of server-side logic. It is commonly used for actions such as POST requests or secure operations that should run on the server. The important thing to understand is that you can call a use server function from a client component, and although the function is invoked from the client, it executes on the server.


Key Points of "use server"

  • Not the opposite of "use client", but rather a server-side function that can be called from the client.
  • Runs exclusively on the server.
  • Ideal for operations such as database calls or secure API requests.


"use server";

export async function getData() {
  console.log("Fetching Data from use Server");
  // Perform server-side operations like database calls here
}        

In this example, the getData() function runs on the server but can be triggered from the client-side using a client component. This pattern allows secure server-side logic to be safely executed from the client, keeping sensitive operations hidden from the browser.


3. server-only

When you need to ensure that a particular function must never be called from the client-side, you use the "server-only" directive. Unlike "use server", which can be invoked by client components (with the execution happening on the server), "server-only" functions can only be executed in server components.

If you try to invoke a "server-only" function from the client-side, you will receive an error.


Error while calling server only function on client side


Key Points of "server-only"

  • Can only be called from server components.
  • Cannot be invoked from client-side components.
  • Used for operations that should be strictly isolated to the server.


import "server-only";

export async function getData2() {
  return "Fetching Data from Server Only";
}        

The getData2() function is strictly for server-side use. You cannot call this function in a client component. Attempting to do so will raise an error.


Converting Client Components to Server Components

In some cases, you may need to call a "server-only" function in your code, but it is not allowed in client components. In these situations, converting your component to a server component is a necessary step.

import { getData2 } from "@/components/actions2";
import React from "react";

const Page = async () => {
  const data = await getData2(); // This function must be called in a server component
  return (
    <>
      <div>{data}</div>
    </>
  );
};

export default Page;        

Here, the entire component is converted to a server component by making it asynchronous and using await to fetch data from the getData2() function. Since this function uses "server-only", calling it in a client component would have caused an error.


Conclusion

In Next.js, understanding how "use client", "use server", and "server-only" function can help you structure your app more efficiently.

  • Use "use client" for browser-specific functionality.
  • Use "use server" for server-side logic that you can trigger from client components.
  • Use "server-only" for strictly server-side logic that cannot be invoked from the client.

要查看或添加评论,请登录

社区洞察