Universal
use server
functions
npm i use-server-directive
yarn add use-server-directive
pnpm add use-server-directive
Like the original "use server"
directive, the compiler supports functions.
async function doStuff(x, y) {
"use server";
await foo(x);
await bar(y);
}
// also works for arrow functions
const doStuff = async (x, y) => {
"use server";
await foo(x);
await bar(y);
};
The compiler also supports async generators
async function* doStuff(x, y) {
"use server";
yield foo(x);
yield bar(y);
}
NOTE Server functions are only valid for async functions.
The original "use server"
is limited to functions, but what if you could mark block statements with the same directives?
if (someCond()) {
'use stuff';
await doStuff();
}
use-server-directive
supports server blocks in almost all statements that supports it:
if-else
try-catch-finally
for
for-in
for-of
for await
while
do-while
- labeled statements
Server blocks also supports break
, continue
, return
and throw
statements, as well as yield
expressions and delegations.
for (const item of items) {
'use server';
await processItem(item);
}
NOTE Server blocks are only supported within async functions and at top-level scope (since modules now support top-level
await
)
use-server-directive
supports closure extraction
async function foo() {
const prefix = 'Message: ';
async function postMessage(message) {
'use server';
await addMessage(prefix + message);
}
}
If a server function returns a value with a Promise
, ReadableStream
or AsyncIterable
, those instances' values are going to be streamed through the response.
async function getMessage() {
'use server';
return {
// `getAsyncData` returns a Promise
// On the client-side, this object is going to
// be received immedatiely, but the value
// to which the Promise resolves into
// is going to be streamed after.
message: getAsyncData(),
};
}
use-server-directive
supports a wide range of data types, you can check the compatibility table here
There are instances where a server function is only imported through a dynamic import, which causes unspecified registration timing, wherein the function might be available on the client but not on the server.
To allow registration of server functions immediately, you can import use-server-directive/preload
on any server entrypoints that will load immediately when the server runs.
import 'use-server-directive/preload';
MIT © lxsmnsyc