What's the best way to integrate PocketBase with Next 14?
Answered
aarvin roshin posted this in #help-forum
![Avatar](https://cdn.discordapp.com/avatars/997149340722274354/2fd4f89a6dab592ac9abcf823c1eb039.webp?size=256)
aarvin roshinOP
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
![Avatar](https://cdn.discordapp.com/avatars/743561772069421169/3c5d689eee4459a24fc420063411c016.webp?size=256)
Ray
it say we can't pass data from middleware to the page but we can still use it in middleware
![Avatar](https://cdn.discordapp.com/avatars/743561772069421169/3c5d689eee4459a24fc420063411c016.webp?size=256)
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
Answer