use-server vs server-only - Next.js app router

use-server vs server-only - Next.js app router

In the Next.js app router's Documentation - we will see these two. Both use server Directive, and server-only seems similar. Let's see how they are different and the cases of using them.

use server :

  • A Server Action can be defined with the React "use server"
  • Server Actions are functions that will get executed on the server only.
  • Server actions can be passed to client components as well but server action will be executed on server only.

Summary: Using the use server directive will enforce that functions will be executed on the server irrespective of where they are invoked. It can be invoked from a client component/server component.


The key purpose of server-only is to put away Server Only code from th client environment. This means, set off functions/function ( which are only meant for server and you don't want to use them in any client component ( declared using "use client" directive ). you need to write import "server-only" at top of file which has Server Only code. if you try to use the any function which has server-only declared in client component next.js will throw an error.To use server-only - you need to install the server-only npm module.

Difference: you can pass server-actions ( declared using the use server directive ) to the client component as well.

Doubt? 🤔 : Can we make a server action using the server-only module . ? Yes, you can, but now that server can't be passed to the client component.

CMD : npm i server-only

Summary: Code marked as Server Only code by importing a server-only module will never reach the browser, and Next.js will complain if you import Server code to client components, and a similar client-only package exists to mark Client code. Say a code needs to access a window object that does not exist on the server but only on the client side ( browser ). In those cases, it will be helpful.

In the end - You can think of server-only as a marker/label to your code, which should not go to any client component or client code. If it goes unintentionally, next will complain.