What is the best way to define common functions in a context?
See original GitHub issueI have an application that I am trying to rewrite from Nuxt to vite-plugin-ssr, but there is some difficulties.
The app uses simple authentication with access token stored in cookies. This token should be used for requests to the remote API via onBeforeRender
and in components (or in an application store). While it’s easy with components and you can create an http-client (fetch
) instance that is available everywhere, with onBeforeRender
it’s quite difficult because this function is outside the app and it is executed both on the server and on the client (when you go from page to page).
Is there any to implement something like this using vite-plugin-ssr
API?
async function onBeforeRender(pageContext: PageContext & PageContextBuiltIn) {
const params = pageContext.routeParams;
const [schedule, latestNews] = await Promise.all([
// user specific schedule
$fetch('schedule'),
// personalised news feed
$fetch('posts', {
query: {
limit: 10,
},
}),
]);
// ...
}
Where $fetch
is a custom fetch function that was created with the app and contains default headers with authorization token.
The same question if I want access the store in onBeforeRender
— is there any way to define context functions before onBeforeRender
in use them in it?
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
Yea it’s not ideal.
I believe what you want is https://github.com/brillout/vite-plugin-ssr/issues/164 which is on the roadmap.
It’s a common use case to want to control the initialization of
pageContext
.You can actually already do that on the server-side (
renderPage(pageContextInit)
) but not on the client-side nor while pre-rendering.Closing in favor of #164.
Let me know if you believe
onInit()
wouldn’t be enough for you.