What's the best way to integrate PocketBase with Next 14?
Answered
aarvin roshin posted this in #help-forum
I'm looking to create an app with PocketBase, but their own SSR guide (https://github.com/pocketbase/js-sdk?tab=readme-ov-file#ssr-integration) seems to be outdated, as it says that Next.js doesn't support middleware. What's the correct way to use PocketBase with Next?
Answered by Ray
const middleware = async (req) => {
const cookie = req.cookies.get(constants.AUTH_COOKIE_NAME)?.value;
const pb = getPocketBase(cookie);
if (cookie) {
const res = NextResponse.next();
pb.authStore.onChange(() => {
res.headers.append(
"Set-Cookie",
`${constants.AUTH_COOKIE_NAME}=${pb.authStore.exportToCookie()}`
);
});
try {
await pb.collection("users").authRefresh();
} catch (e) {
const res = NextResponse.redirect(new URL("/login", req.url));
pb.authStore.clear();
res.cookies.delete(constants.AUTH_COOKIE_NAME);
return res;
}
return res;
}
}
something like this
3 Replies
it say we can't pass data from middleware to the page but we can still use it in middleware
const middleware = async (req) => {
const cookie = req.cookies.get(constants.AUTH_COOKIE_NAME)?.value;
const pb = getPocketBase(cookie);
if (cookie) {
const res = NextResponse.next();
pb.authStore.onChange(() => {
res.headers.append(
"Set-Cookie",
`${constants.AUTH_COOKIE_NAME}=${pb.authStore.exportToCookie()}`
);
});
try {
await pb.collection("users").authRefresh();
} catch (e) {
const res = NextResponse.redirect(new URL("/login", req.url));
pb.authStore.clear();
res.cookies.delete(constants.AUTH_COOKIE_NAME);
return res;
}
return res;
}
}
something like this
Answer