HTTP Headers
Request
You can access the headers of the incoming HTTP Request at:
pageContext.headers
pageContext.headersOriginal
pageContext.headers
is a string object (Record<string, string>
) normalized by Vike, and pageContext.headersOriginal
is the original object (unknown
) provided by the server.
For example:
// pageContext.headers
{
'accept-encoding': 'gzip, br',
'accept-language': 'en-US,en;q=0.9,fr;q=0.8',
'cache-control': 'max-age=0',
connection: 'Keep-Alive',
cookie: 'username=brillout; admin=true'
}
// pageContext.headersOriginal
[
['Accept-Encoding', 'gzip, br'],
['Accept-Language', 'en-US,en;q=0.9,fr;q=0.8']
['Cache-Control', 'max-age=0'],
['Connection', 'Keep-Alive'],
['Cookie', 'username=brillout; admin=true']
]
You can also have the headers as a standard Headers
object by using new Headers()
:
// The `new Headers()` constructor is available in all common JavaScript environments:
// Node.js, Cloudflare Workers, browsers, ...
const headers = new Headers(pageContext.headers)
All values are merged, and you can get the list of values as an array (string[]
):
const acceptLanguage = pageContext.headers['accept-language']
.split(',')
.map(v => v.trimStart())
For getting the list of cookie values, you usually use a cookie parser (e.g. cookie-parser
).
The pageContext.headersOriginal
value is defined at your renderPage()
integration:
import { renderPage } from 'vike/server'
// Server middleware
app.get('*', async (req) => {
const pageContextInit = {
urlOriginal: req.url,
headersOriginal: req.headers
}
const pageContext = await renderPage(pageContextInit)
// ...
})
Response
The headers of the HTTP Response that is generated by Vike is available at pageContext.httpResponse.headers
.
import { renderPage } from 'vike/server'
// Server middleware
app.get('*', async (req) => {
// ...
const pageContext = await renderPage(pageContextInit)
// HTTP Headers of the HTTP Response.
const headers = pageContext.httpResponse.headers
})
See API >
renderPage()
.
It's an array of string tuples ([string, string][]
) such as:
[
['Content-Type', 'text/html;charset=utf-8'],
['Cache-Control', 'no-store, max-age=0']
]
You can also have the headers as a standard Headers
object by using new Headers()
:
const pageContext = await renderPage(pageContextInit)
// The `new Headers()` constructor is available in all common JavaScript environments:
// Node.js, Cloudflare Workers, browsers, ...
const headers = new Headers(pageContext.httpResponse.headers)