use-server-directive v0.4.3
use-server-directive
Universal
use serverfunctions
Install
npm i use-server-directiveyarn add use-server-directivepnpm add use-server-directiveFeatures
Server functions
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.
Server blocks
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-elsetry-catch-finallyforfor-infor-offor awaitwhiledo-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)
Closure extraction
use-server-directive supports closure extraction
async function foo() {
const prefix = 'Message: ';
async function postMessage(message) {
'use server';
await addMessage(prefix + message);
}
}Streaming server functions
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(),
};
}Advanced serialization
use-server-directive supports a wide range of data types, you can check the compatibility table here
Customizable directive
Integrations
Examples
Preloading
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';Sponsors
License
MIT © lxsmnsyc