mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-21 21:25:11 +00:00
feat(nuxt): add useResponseHeader
composable (#27131)
This commit is contained in:
parent
90025976f8
commit
3f3d416769
48
docs/3.api/2.composables/use-response-header.md
Normal file
48
docs/3.api/2.composables/use-response-header.md
Normal file
@ -0,0 +1,48 @@
|
||||
---
|
||||
title: "useResponseHeader"
|
||||
description: "Use useResponseHeader to set a server response 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
|
||||
---
|
||||
|
||||
::important
|
||||
This composable is available in Nuxt v3.14+.
|
||||
::
|
||||
|
||||
You can use the built-in [`useResponseHeader`](/docs/api/composables/use-response-header) composable to set any server response header within your pages, components, and plugins.
|
||||
|
||||
```ts
|
||||
// Set the a custom response header
|
||||
const header = useResponseHeader('X-My-Header');
|
||||
header.value = 'my-value';
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
We can use `useResponseHeader` to easily set a response header on a per-page basis.
|
||||
|
||||
```vue [pages/test.vue]
|
||||
<script setup>
|
||||
// pages/test.vue
|
||||
const header = useResponseHeader('X-My-Header');
|
||||
header.value = 'my-value';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>Test page with custom header</h1>
|
||||
<p>The response from the server for this "/test" page will have a custom "X-My-Header" header.</p>
|
||||
</template>
|
||||
```
|
||||
|
||||
We can use `useResponseHeader` for example in Nuxt [middleware](/docs/guide/directory-structure/middleware) to set a response header for all pages.
|
||||
|
||||
```ts [middleware/my-header-middleware.ts]
|
||||
export default defineNuxtRouteMiddleware((to, from) => {
|
||||
const header = useResponseHeader('X-My-Always-Header');
|
||||
header.value = `I'm Always here!`;
|
||||
});
|
||||
|
||||
```
|
@ -24,7 +24,7 @@ export { useFetch, useLazyFetch } from './fetch'
|
||||
export type { FetchResult, UseFetchOptions } from './fetch'
|
||||
export { useCookie, refreshCookie } from './cookie'
|
||||
export type { CookieOptions, CookieRef } from './cookie'
|
||||
export { onPrehydrate, prerenderRoutes, useRequestHeaders, useRequestEvent, useRequestFetch, setResponseStatus } from './ssr'
|
||||
export { onPrehydrate, prerenderRoutes, useRequestHeaders, useRequestEvent, useRequestFetch, setResponseStatus, useResponseHeader } from './ssr'
|
||||
export { onNuxtReady } from './ready'
|
||||
export { abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, onBeforeRouteLeave, onBeforeRouteUpdate, setPageLayout, navigateTo, useRoute, useRouter } from './router'
|
||||
export type { AddRouteMiddlewareOptions, RouteMiddleware } from './router'
|
||||
|
@ -1,6 +1,6 @@
|
||||
import type { H3Event } from 'h3'
|
||||
import { setResponseStatus as _setResponseStatus, appendHeader, getRequestHeader, getRequestHeaders } from 'h3'
|
||||
import { getCurrentInstance } from 'vue'
|
||||
import { setResponseStatus as _setResponseStatus, appendHeader, getRequestHeader, getRequestHeaders, getResponseHeader, removeResponseHeader, setResponseHeader } from 'h3'
|
||||
import { computed, getCurrentInstance, ref } from 'vue'
|
||||
import { useServerHead } from '@unhead/vue'
|
||||
|
||||
import type { NuxtApp } from '../nuxt'
|
||||
@ -61,6 +61,34 @@ export function setResponseStatus (arg1: H3Event | number | undefined, arg2?: nu
|
||||
}
|
||||
}
|
||||
|
||||
/** @since 3.14.0 */
|
||||
export function useResponseHeader (header: string) {
|
||||
if (import.meta.client) {
|
||||
if (import.meta.dev) {
|
||||
return computed({
|
||||
get: () => undefined,
|
||||
set: () => console.warn('[nuxt] Setting response headers is not supported in the browser.'),
|
||||
})
|
||||
}
|
||||
return ref()
|
||||
}
|
||||
|
||||
const event = useRequestEvent()!
|
||||
|
||||
return computed({
|
||||
get () {
|
||||
return getResponseHeader(event, header)
|
||||
},
|
||||
set (newValue) {
|
||||
if (!newValue) {
|
||||
return removeResponseHeader(event, header)
|
||||
}
|
||||
|
||||
return setResponseHeader(event, header, newValue)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** @since 3.8.0 */
|
||||
export function prerenderRoutes (path: string | string[]) {
|
||||
if (!import.meta.server || !import.meta.prerender) { return }
|
||||
|
@ -1,7 +1,7 @@
|
||||
export { applyPlugin, applyPlugins, callWithNuxt, createNuxtApp, defineAppConfig, defineNuxtPlugin, definePayloadPlugin, isNuxtPlugin, registerPluginHooks, tryUseNuxtApp, useNuxtApp, useRuntimeConfig } from './nuxt'
|
||||
export type { CreateOptions, NuxtApp, NuxtPayload, NuxtPluginIndicator, NuxtSSRContext, ObjectPlugin, Plugin, PluginEnvContext, PluginMeta, ResolvedPluginMeta, RuntimeNuxtHooks } from './nuxt'
|
||||
|
||||
export { defineNuxtComponent, useAsyncData, useLazyAsyncData, useNuxtData, refreshNuxtData, clearNuxtData, useHydration, callOnce, useState, clearNuxtState, clearError, createError, isNuxtError, showError, useError, useFetch, useLazyFetch, useCookie, refreshCookie, onPrehydrate, prerenderRoutes, useRequestHeaders, useRequestEvent, useRequestFetch, setResponseStatus, onNuxtReady, abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, onBeforeRouteLeave, onBeforeRouteUpdate, setPageLayout, navigateTo, useRoute, useRouter, preloadComponents, prefetchComponents, preloadRouteComponents, isPrerendered, loadPayload, preloadPayload, definePayloadReducer, definePayloadReviver, getAppManifest, getRouteRules, reloadNuxtApp, useRequestURL, usePreviewMode, useId, useRouteAnnouncer, useHead, useSeoMeta, useServerSeoMeta } from './composables/index'
|
||||
export { defineNuxtComponent, useAsyncData, useLazyAsyncData, useNuxtData, refreshNuxtData, clearNuxtData, useHydration, callOnce, useState, clearNuxtState, clearError, createError, isNuxtError, showError, useError, useFetch, useLazyFetch, useCookie, refreshCookie, onPrehydrate, prerenderRoutes, useRequestHeaders, useRequestEvent, useRequestFetch, setResponseStatus, useResponseHeader, onNuxtReady, abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, onBeforeRouteLeave, onBeforeRouteUpdate, setPageLayout, navigateTo, useRoute, useRouter, preloadComponents, prefetchComponents, preloadRouteComponents, isPrerendered, loadPayload, preloadPayload, definePayloadReducer, definePayloadReviver, getAppManifest, getRouteRules, reloadNuxtApp, useRequestURL, usePreviewMode, useId, useRouteAnnouncer, useHead, useSeoMeta, useServerSeoMeta } from './composables/index'
|
||||
export type { AddRouteMiddlewareOptions, AsyncData, AsyncDataOptions, AsyncDataRequestStatus, CookieOptions, CookieRef, FetchResult, NuxtAppManifest, NuxtAppManifestMeta, NuxtError, ReloadNuxtAppOptions, RouteMiddleware, UseFetchOptions } from './composables/index'
|
||||
|
||||
export { defineNuxtLink } from './components/index'
|
||||
|
@ -66,7 +66,7 @@ const granularAppPresets: InlinePreset[] = [
|
||||
from: '#app/composables/cookie',
|
||||
},
|
||||
{
|
||||
imports: ['onPrehydrate', 'prerenderRoutes', 'useRequestHeader', 'useRequestHeaders', 'useRequestEvent', 'useRequestFetch', 'setResponseStatus'],
|
||||
imports: ['onPrehydrate', 'prerenderRoutes', 'useRequestHeader', 'useRequestHeaders', 'useResponseHeader', 'useRequestEvent', 'useRequestFetch', 'setResponseStatus'],
|
||||
from: '#app/composables/ssr',
|
||||
},
|
||||
{
|
||||
|
@ -12,7 +12,7 @@ import * as composables from '#app/composables'
|
||||
import { clearNuxtData, refreshNuxtData, useAsyncData, useNuxtData } from '#app/composables/asyncData'
|
||||
import { clearError, createError, isNuxtError, showError, useError } from '#app/composables/error'
|
||||
import { onNuxtReady } from '#app/composables/ready'
|
||||
import { setResponseStatus, useRequestEvent, useRequestFetch, useRequestHeaders } from '#app/composables/ssr'
|
||||
import { setResponseStatus, useRequestEvent, useRequestFetch, useRequestHeaders, useResponseHeader } from '#app/composables/ssr'
|
||||
import { clearNuxtState, useState } from '#app/composables/state'
|
||||
import { useRequestURL } from '#app/composables/url'
|
||||
import { getAppManifest, getRouteRules } from '#app/composables/manifest'
|
||||
@ -83,6 +83,7 @@ describe('composables', () => {
|
||||
'useRequestFetch',
|
||||
'isPrerendered',
|
||||
'useRequestHeaders',
|
||||
'useResponseHeader',
|
||||
'useCookie',
|
||||
'clearNuxtState',
|
||||
'useState',
|
||||
@ -394,6 +395,7 @@ describe('ssr composables', () => {
|
||||
expect(useRequestFetch()).toEqual($fetch)
|
||||
expect(useRequestHeaders()).toEqual({})
|
||||
expect(prerenderRoutes('/')).toBeUndefined()
|
||||
expect(useResponseHeader('x-test').value).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user