Next.js Discord

Discord Forum

Handling state management - current user?

Unanswered
Norwegian Forest Cat posted this in #help-forum
Open in Discord
Norwegian Forest CatOP
Hey,

I am a complete newbie to Next.js but have some experience with React, React Native (Expo) and so on.
I have Pocketbase as a backend and I am using Pocketbase SDK (https://github.com/pocketbase/js-sdk#authstore) in my NextJS app.

My middleware.ts:
async function middleware(request: NextRequest) {
    const response = NextResponse.next();
    const requestCookie = request.cookies.get("pb_auth");

    const cookie = await getNextjsCookie(requestCookie);
    const pb = new PocketBase(process.env.NEXT_PUBLIC_PB_URL);

    if (cookie)
    {
        try
        {
            pb.authStore.loadFromCookie(cookie);
        }
        catch (error)
        {
            pb.authStore.clear();
            response.headers.set("set-cookie", pb.authStore.exportToCookie({ httpOnly: false }));
        }
    }

    try
    {
        pb.authStore.isValid && (await pb.collection(PB_USERS).authRefresh());
    }
    catch (err)
    {
        pb.authStore.clear();
        response.headers.set(
            "set-cookie",
            pb.authStore.exportToCookie({ httpOnly: false }));
    }

    // Redirecting based on `pb.authStore.model`

    return response;
}

I have so far managed to get simple OAuth authentication working - I get cookie saved and my authenticated user is stored in pb.authStore I also set document.cookie after authenticating.

Now let's get to the question and part I am confused about.
1. I do authentication on client component.
2. Authorized part of my app I would like to do SSR.

I would like to use something like Jotai to store my curUser. (started with Redux, but felt like overkill for my size of an app).

- I obviously can't access React hooks in middleware - right? So I can't after refreshing my auth set my state, or set user on every request.
- Can I perhaps use root layout? If so, how?
- Where else can I then load my user from my JWT? What's the best practice to have user both on client and server components?

0 Replies