The Pocketbase SDK assumes SPA by default and saves the auth response in the local storage , while you can do this in the app directory or other SSR first frameworks , it will give you hydration errors as the state goes from unauthenticated on the server to authenticated on the client which will cause a html mismatch if for example you were rendering a user profile picture if a user exists .
Pocketbase has an exportToCookie which helps with this issue . The Nextjs13 integration is a little more tedious compared to the other frameworks.
First step is picking server or client login , this example ha s a server component and actions example included too ,but you'll have to setup some logic to sync the cookie with the client,
- Client side on the client we create a simple login component and call
1export async function loginUser({ pb,user, password }: ILoginUser) {
2 try {
3 const authData = await pb.collection(pb_user_collection)
4 .authWithPassword<PBUserRecord>(user, password);
5 return authData;
6 } catch (error) {
7 throw error;
8 }
9}
1 const handleSubmit = async (e: React.FormEvent) => {
2 e.preventDefault();
3 try {
4 const pb_user = await loginUser({
5 pb,
6 user: user.identity,
7 password: user.password,
8 });
9
10 document.cookie = pb.authStore.exportToCookie({ httpOnly: false });
11 if (search_params) {
12
13 router.push(search_params);
14 } else {
15 router.push("/");
16 }
17
18 return pb_user;
19 } catch (error: any) {
20 console.log("error logging in user === ", error.originalError);
21 throw error;
22 }
23 };
- Middleware : Next13 uses middleware to do
auth guarding , assuming the /admin page needs authentication and homepage can be used without a login
add a middleware.ts in our root directory , in my case am using src/app so it'll be in the src directory
```ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import PocketBase from "pocketbase";
import { pb_url, pb_user_collection } from "./state/consts";
import { getNextjsCookie } from "./state/utils/server-cookie";
export async function middleware(request: NextRequest) {
const response = NextResponse.next();
const request_cookie = request.cookies.get("pb_auth") // console.log("middlware request cookie ===",)