feat(nuxt): useRequestHeader utility (#24781)

This commit is contained in:
Michael Brevard 2023-12-16 11:08:56 +02:00 committed by GitHub
parent fe2f0e01f2
commit 40a5f44942
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 42 additions and 2 deletions

View File

@ -0,0 +1,34 @@
---
title: "useRequestHeader"
description: "Use useRequestHeader to access a certain incoming request header."
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/ssr.ts
size: xs
---
You can use the built-in [`useRequestHeader`](/docs/api/composables/use-request-header) composable to access any incoming request header within your pages, components, and plugins.
```ts
// Get the authorization request header
const authorization = useRequestHeader('authorization')
```
::callout
In the browser, `useRequestHeader` will return `undefined`.
::
## Example
We can use `useRequestHeader` to easily figure out if a user is authorized or not.
The example below reads the `authorization` request header to find out if a person can access a restricted resource.
```ts [middleware/authorized-only.ts]
export default defineNuxtRouteMiddleware((to, from) => {
if (!useRequestHeader('authorization')) {
return navigateTo('/not-authorized')
}
})
```

View File

@ -1,5 +1,5 @@
import type { H3Event } from 'h3'
import { setResponseStatus as _setResponseStatus, appendHeader, getRequestHeaders } from 'h3'
import { setResponseStatus as _setResponseStatus, appendHeader, getRequestHeader, getRequestHeaders } from 'h3'
import type { NuxtApp } from '../nuxt'
import { useNuxtApp } from '../nuxt'
@ -17,6 +17,12 @@ export function useRequestHeaders (include?: any[]) {
return Object.fromEntries(include.map(key => key.toLowerCase()).filter(key => headers[key]).map(key => [key, headers[key]]))
}
export function useRequestHeader(header: string) {
if (import.meta.client) { return undefined }
const event = useRequestEvent()
return event ? getRequestHeader(event, header) : undefined
}
export function useRequestFetch (): typeof global.$fetch {
if (import.meta.client) {
return globalThis.$fetch

View File

@ -58,7 +58,7 @@ const granularAppPresets: InlinePreset[] = [
from: '#app/composables/cookie'
},
{
imports: ['prerenderRoutes', 'useRequestHeaders', 'useRequestEvent', 'useRequestFetch', 'setResponseStatus'],
imports: ['prerenderRoutes', 'useRequestHeader', 'useRequestHeaders', 'useRequestEvent', 'useRequestFetch', 'setResponseStatus'],
from: '#app/composables/ssr'
},
{