@rsc-kit/mcp
Version:
An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.
141 lines (106 loc) • 4.66 kB
Markdown
# Headers and cookies
> Reading request headers and cookies, setting response headers and cookies, and security headers.
Read headers and cookies anywhere on the server. Set them in a middleware:
```tsx
import { cookies } from '@rsc-kit/core/request'
export default async function Page() {
const jar = await cookies()
return <p>Hello {jar.get('name')?.value ?? 'stranger'}</p>
}
```
## Reading headers and cookies
In a server component or an action:
```tsx
import { headers, cookies, searchParams } from '@rsc-kit/core/request'
const h = await headers()
const jar = await cookies()
```
## Setting headers and cookies
Set them in a `middleware.ts`:
```tsx
import { responseHeaders, cookies } from '@rsc-kit/core/request'
export async function middleware() {
responseHeaders().set('X-Frame-Options', 'DENY')
const jar = await cookies()
jar.set('last-seen', new Date().toISOString(), { httpOnly: true, path: '/' })
}
```
**Only middleware can set them.** It runs before the render, while the response
headers haven't been sent. A component runs while the page streams, after
they have, so setting one from a component throws.
A redirect carries them too, so a middleware can remember where someone was
going before sending them to sign in:
```tsx
export async function middleware() {
const jar = await cookies()
if (!jar.get('session')) {
jar.set('intended', '/dashboard', { path: '/' })
redirect('/login')
}
}
```
### Cookie options
```ts
jar.set('name', 'value', {
httpOnly: true,
secure: true,
sameSite: 'lax', // 'strict' | 'lax' | 'none'
path: '/',
maxAge: 60 * 60 * 24,
expires: new Date('2027-01-01'),
})
```
Names, `sameSite` and `expires` are checked, so a typo is an error rather than
a header the browser quietly ignores.
### A cookie you set is the one you read
For the rest of the request, `cookies().get()` returns the value you set, not
what the browser sent. That includes the sections an action `revalidate()`s,
which render in the same request. A deleted cookie is gone from `get`, `has`
and `getAll`. So an action that does `jar.set('agent', id)` then
`revalidate('all')` gets a sidebar rendered with the new choice. Next.js works
the same way. The next request starts from what the browser sends.
## Security headers
Nothing sets security headers for you. The ones that are the same on every page go in the config:
```ts title="vite.config.ts"
rscKit({
headers: {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'X-Frame-Options': 'DENY',
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains',
},
})
```
Every response gets them.
They are fixed for the build, so a page can still be
[served from an edge's cache](/guides/edge-caching) with them. Only headers an
edge can send with a cached page are accepted: `Content-Language`,
`X-Robots-Tag`, `Content-Security-Policy`,
`Content-Security-Policy-Report-Only`, `Permissions-Policy`,
`Referrer-Policy`, `Strict-Transport-Security`, `X-Frame-Options`,
`X-Content-Type-Options`, `Cross-Origin-Opener-Policy`,
`Cross-Origin-Embedder-Policy`, `Cross-Origin-Resource-Policy` and
`X-DNS-Prefetch-Control`. Anything else is a build error. `Cache-Control` and
`Link` are left out because the renderer sets them per response.
- **A header that depends on the request** goes in a middleware. A middleware's
value for a header wins over the config's. A page under a middleware is never
served from an edge's cache, so a root `middleware.ts` keeps every page out.
- **`Content-Security-Policy`** needs each page's inline code allowed. Use
[`contentSecurityPolicy`](/guides/content-security-policy), which adds the
hashes, and a nonce where the page streams.
## Headers rsc-kit sets
**`X-RSC-Kit`** says how a response was served: `stored` (a page the build
wrote), `rendered` (rendered for this visitor) or `shell` (a stored shell with
its holes rendered now). Check it in the Network tab when a page is slower
than expected, or key a CDN rule or health check on it. It's the equivalent of
`X-Nextjs-Cache`. Under `vite dev`, where every page is rendered, the badge in
the corner of the page says how production will answer it and why: see
[Seeing why while you work](/guides/static-generation#seeing-why-while-you-work).
**`X-Powered-By: rsc-kit`** on every response, and
`<meta name="generator" content="rsc-kit">` in every document, name the
framework but never its version. To turn both off:
```ts title="vite.config.ts"
rscKit({ identify: false })
```
A proxy can strip the header but not the tag inside the HTML, which is why
the option exists.