Skip to content
You are reading the v2 docs, currently in beta.V1 docs
oRPC
Esc
↑↓navigate↵open⌘Jpreview
On this page

Cookie Jar Plugin

Store the cookies servers set and send them back on later requests, like a browser, for server-side clients.

Clients outside a browser, such as during server-side rendering, in scripts, or in tests, do not keep cookies. CookieJarLinkPlugin stores the cookies servers set and sends them back on later requests, following the browser rules of RFC 6265.

Setup

import { CookieJarLinkPlugin } from '@orpc/client/plugins'

const origin = 'https://api.example.com'

const link = new RPCLink({
  origin,
  plugins: [
    new CookieJarLinkPlugin({ origin }), // <- same origin as the link
  ],
})

The plugin does nothing when origin is undefined or relative, as in a browser, which handles cookies itself. A cookie header you set, such as through the link’s headers option, wins over jar cookies with the same name.

Custom Jar

Pass your own CookieJar to read, clear, or share cookies between links:

import { CookieJar, CookieJarLinkPlugin } from '@orpc/client/plugins'

const jar = new CookieJar()

const link = new RPCLink({
  origin,
  plugins: [new CookieJarLinkPlugin({ origin, jar })],
})

jar.getCookies() // <- stored cookies
jar.clear()

The jar has no public suffix list, so a site could set a cookie for all of .com. Only share a jar between sites you trust.

Per-Request Jar

jar also accepts a function, so one link can keep a jar per user:

const link = new RPCLink<{ jar: CookieJar }>({
  origin,
  plugins: [
    new CookieJarLinkPlugin({
      origin,
      jar: ({ context }) => context.jar,
    }),
  ],
})

Learn More

For implementation details, see the CookieJarLinkPlugin source code.

Last updated on

Was this page helpful?