Next.js Discord

Discord Forum

Passing data from middleware to server components

Alaska pollock posted this in #help-forum
Open in Discord
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:

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 =

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

  const pb = new PocketBase(URL)

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

    response.cookies.set(name, value)


  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

no, we can't.
their readme show how to integrate pb to nextjs

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