Next.js Discord

Discord Forum

Passing data from middleware to server components

Unanswered
Alaska pollock posted this in #help-forum
Open in Discord
Avatar
Alaska pollockOP
Is it possible to pass data from middleware to server components in any convinent way, other than using headers?

In my case I need to pass a pocketbase sdk instance created in the middleware (need to access auth cookie) and pass it to the server components without need to recreate the same instance.

Here is my code:

middleware.ts:
import { NextRequest, NextResponse } from 'next/server'
import PocketBase from 'pocketbase'
import { URL } from './lib/pocketbase'
import { decodeNextCookie, encodePbCookie } from './utils/cookies'

export async function middleware(request: NextRequest) {
  const response = NextResponse.next()

  const encodedNextAuthCookie = request.cookies.get('pb_auth')
  const decodedNextAuthCookie = encodedNextAuthCookie
    ? decodeNextCookie(encodedNextAuthCookie)
    : ''

  const pb = new PocketBase(URL)

  pb.authStore.loadFromCookie(decodedNextAuthCookie)
  pb.authStore.onChange(() => {
    const { name, value } = encodePbCookie(pb.authStore.exportToCookie())

    response.cookies.set(name, value)
  })

  console.log(pb.authStore)

  return response
}


The sign in is being done on the client side. To do so I needed to set the auth cookie (by default auth token is stored in local storaged)

useEffect(() => {
    pb.authStore.onChange(() => {
      document.cookie = pb.authStore.exportToCookie({ httpOnly: false })
      setUser(pb.authStore.model as User)
    })
  }, [])

1 Reply

Avatar
Ray
no, we can't.
their readme show how to integrate pb to nextjs
https://github.com/pocketbase/js-sdk#ssr-integration

we gotta re-create the instance with the cookies.
and I think its better to handle authentication on the server side and set the httponly cookies afterward