How to implement the init$ function #208
-
QuestionHello to the development team of We are currently trying to implement the https://react-server.dev/ja/router/server-routing#middlewares Implemented.I have implemented the “use server”;.
import { redirect } from “@lazarv/react-server”;
export async function init$() {
console.log(“[INIT$] Function called during initialization”);
return async function middleware(context) {
“use server”;
try {
console.log(“[INIT$-MW] Context received”);
if (context?.url instanceof URL) {
const pathname = context.url.pathname;
console.log(“[INIT$-MW] Path detected:”, pathname);
if (pathname.includes(“/dashboard”)) {
console.log(“[INIT$-MW] Redirecting dashboard -> login”); return redirect(“/login”)
return redirect(“/login”); }
}
}
} catch (err) {
console.error(“[INIT$-MW] Error:”, err); }
}
} return undefined; }
}; }
} Problems occurring.
What we tried
Questions
On the other hand, the middleware implementation by Thank you in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi @kooooo1tktn! To make The You don't need to add a "use server" directive in middlewares or the entry module, as this directive exposes all exported functions from a module to be consumable as server functions, which are callable by a client. You can use any HTTP context helpers the framework provides inside a middleware. You don't need to manually extract information from the input HTTP context received in the handler function returned by The documentation app uses similar logic as you have in your provided code, so please check it out at https://github.com/lazarv/react-server/blob/main/docs/src/pages/(i18n).middleware.mjs Documentation regarding middlewares using the file-system based router is at https://react-server.dev/ja/router/middlewares I hope this helps. Please let me know if any part needs more clarification. |
Beta Was this translation helpful? Give feedback.
Hi @kooooo1tktn!
To make
init$
work, you need to export it from your entry module. Based on your description, you use the built-in file-system based router, which supports middleware files instead of theinit$
function.The
init$
function only works when using@lazarv/react-server
directly with a React Server Component entry, likereact-server ./App.jsx
and theApp.jsx
file exports aninit$
function.You don't need to add a "use server" directive in middlewares or the entry module, as this directive exposes all exported functions from a module to be consumable as server functions, which are callable by a client.
You can use any HTTP context helpers the framework provides inside a middlewa…