T
TanStack3mo ago
sensitive-blue

server side context?

I am trying to implement pocketbase auth and currently I do:
export const authenticate = createServerFn().handler(async () => {
pb.authStore.loadFromCookie(getCookie(cookieName) || '');

try {
pb.authStore.isValid && (await pb.collection('users').authRefresh());
} catch {
pb.authStore.clear();
}

setCookie(cookieName, pb.authStore.exportToCookie());

return { record: pb.authStore.record };
})

// _auth.tsx route
beforeLoad: async ({ context }) => {
const data = await authenticate();
if (!data.record) throw redirect({ to: '/login' });
return { ...context, record: data.record };
},
export const authenticate = createServerFn().handler(async () => {
pb.authStore.loadFromCookie(getCookie(cookieName) || '');

try {
pb.authStore.isValid && (await pb.collection('users').authRefresh());
} catch {
pb.authStore.clear();
}

setCookie(cookieName, pb.authStore.exportToCookie());

return { record: pb.authStore.record };
})

// _auth.tsx route
beforeLoad: async ({ context }) => {
const data = await authenticate();
if (!data.record) throw redirect({ to: '/login' });
return { ...context, record: data.record };
},
the problem is pocketbase instace is created once during server startup, but I want to create a new instance for each request but I'm struggling to figure out how to do that in start.
5 Replies
sunny-green
sunny-green3mo ago
Create a middleware that instantiate the instance. (i hope i do get your point, feel free to counter if you feel like i don't)
const pocketBaseMiddleware = createMiddleware({
type: "function" /* or "request" for Server Routes */
}).server(async (ctx) => {
return ctx.next({
context: {
pb: new PocketBase('<url>')
}
})
})
const pocketBaseMiddleware = createMiddleware({
type: "function" /* or "request" for Server Routes */
}).server(async (ctx) => {
return ctx.next({
context: {
pb: new PocketBase('<url>')
}
})
})
sensitive-blue
sensitive-blueOP3mo ago
odd, i swear I tried it and got serialization error, but this works! but now I'm having another issue, my server functions throw redirect doesnt work anymore
sunny-green
sunny-green3mo ago
GitHub
Can't redirect in server functions with middleware · Issue #4460 ...
Which project does this relate to? Start Describe the bug Throwing redirects in server functions that use middleware doesn&#39;t work. It works fine if I remove the middleware. I am using the useSe...
other-emerald
other-emerald3mo ago
we are currently reworking all of this so this will be fixed soon
sensitive-blue
sensitive-blueOP3mo ago
thanks for the hard work

Did you find this page helpful?