Next.js Discord

Discord Forum

Share request context with external library

Unanswered
American Fuzzy Lop posted this in #help-forum
Open in Discord
American Fuzzy LopOP
Hi, I would like to share some data with an external library. The data are some search params of the current Url, full Url, origin and path. My first try was to use middleware and set this data into headers in the app and use headers() in the library. Unfortunately this is not working (I think because the external library does not really share the same next context?). Then I gave the AsyncLocalStorage a try, but same problem here. Does anyone know if this is even possible?

1 Reply

American Fuzzy LopOP
Here is a code example of my headers() try:

This is library code:
export function setCraftSiteHeaders(res: NextResponse, req: NextRequest) {
  const fullUrl = req.nextUrl.href
  const origin = req.nextUrl.origin
  const path = req.nextUrl.pathname
  res.headers.set(SITE_HEADERS.URL, fullUrl)
  res.headers.set(SITE_HEADERS.ORIGIN, origin)
  res.headers.set(SITE_HEADERS.PATH, path)
  return res
}
export async function getCraftSiteHeaders() {
  const hdrs = await headers()
  return {
    origin: hdrs.get(SITE_HEADERS.ORIGIN),
    path: hdrs.get(SITE_HEADERS.PATH),
    url: hdrs.get(SITE_HEADERS.URL),
  }
}


This is the next middleware:
export function middleware(req: NextRequest) {
  let res = NextResponse.next()
  res = setCraftSiteHeaders(res, req)
  return res
}

export const config = {
  matcher: '/((?!api|trpc|_next|_vercel|.*\\..*).*)',
}


That's how I want to use it in the next home page:
export default async function Home() {
  const siteHeaders = await getCraftSiteHeaders()
  return <div>...</div>
}


By the way, if all the code for that runs in the next app directly, it works.