diff --git a/docs/content/3.docs/1.usage/1.data-fetching.md b/docs/content/3.docs/1.usage/1.data-fetching.md index e8a6e6cf3f..feaf5697fe 100644 --- a/docs/content/3.docs/1.usage/1.data-fetching.md +++ b/docs/content/3.docs/1.usage/1.data-fetching.md @@ -117,6 +117,36 @@ const { data } = await useFetch('/api/count') This composable behaves identically to `useFetch` with the `lazy: true` option set. In other words, the async function does not block navigation. That means you will need to handle the situation where the data is `null` (or whatever value you have provided in a custom `default` factory function). +## Isomorphic fetch + +When we call `fetch` in the browser, user headers like `cookie` will be directly sent to the API. +But during server-side-rendering, since the `fetch` request is originating from the server, it doesn't include the user's browser cookies. + +We can use [`useRequestHeaders`](/docs/usage/ssr) to access and proxy cookies to the API from server-side. + +**Example:** + +The example below adds the request headers to an isomorphic `fetch` call to ensure that the API endpoint has access to the same `cookie` header originally sent by the user. + +```vue + +``` + +::alert{type="warning"} +Be very careful before proxy headers to an external API and include headers that you need. +Not all headers are safe to be bypassed and might introduce unwanted behavior. +Here is a list of common headers that are NOT to be proxied: + +* `host`, `accept` +* `content-length`, `content-md5`, `content-type` +* `x-forwarded-host`, `x-forwarded-port`, `x-forwarded-proto` +* `cf-connecting-ip`, `cf-ray` +:: + ## Best practices The data returned by these composables will be stored inside the page payload. This means that every key returned that is not used in your component will be added to the payload. diff --git a/docs/content/3.docs/1.usage/7.ssr.md b/docs/content/3.docs/1.usage/7.ssr.md new file mode 100644 index 0000000000..de0faf6021 --- /dev/null +++ b/docs/content/3.docs/1.usage/7.ssr.md @@ -0,0 +1,19 @@ +# SSR utilities + +Nuxt provides composables and utilities for first-class server-side-rendering support. + +## useRequestHeaders + +Within your pages, components, and plugins you can use `useRequestHeaders` to access the incoming request headers. + +```js +// Get all request headers +const headers = useRequestHeaders() + +// Get only cookie request header +const headers = useRequestHeaders(['cookie']) +``` + +::alert{icon=👉} +On client side, `useRequestHeaders` will return an empty object. +:: diff --git a/packages/bridge/src/runtime/composables.ts b/packages/bridge/src/runtime/composables.ts index 4e3474e770..24cd287b93 100644 --- a/packages/bridge/src/runtime/composables.ts +++ b/packages/bridge/src/runtime/composables.ts @@ -9,6 +9,7 @@ import { useNuxtApp } from './app' export { useLazyAsyncData } from './asyncData' export { useLazyFetch } from './fetch' export { useCookie } from './cookie' +export { useRequestHeaders } from './ssr' export * from '@vue/composition-api' diff --git a/packages/bridge/src/runtime/ssr.ts b/packages/bridge/src/runtime/ssr.ts new file mode 120000 index 0000000000..57287eb34c --- /dev/null +++ b/packages/bridge/src/runtime/ssr.ts @@ -0,0 +1 @@ +../../../nuxt3/src/app/composables/ssr.ts \ No newline at end of file diff --git a/packages/nuxt3/src/app/composables/index.ts b/packages/nuxt3/src/app/composables/index.ts index 0344c0ef24..b69f7b3160 100644 --- a/packages/nuxt3/src/app/composables/index.ts +++ b/packages/nuxt3/src/app/composables/index.ts @@ -4,3 +4,4 @@ export { useHydration } from './hydrate' export { useState } from './state' export { useFetch, useLazyFetch } from './fetch' export { useCookie } from './cookie' +export { useRequestHeaders } from './ssr' diff --git a/packages/nuxt3/src/app/composables/ssr.ts b/packages/nuxt3/src/app/composables/ssr.ts new file mode 100644 index 0000000000..f4fcf88309 --- /dev/null +++ b/packages/nuxt3/src/app/composables/ssr.ts @@ -0,0 +1,11 @@ +/* eslint-disable no-redeclare */ +import { useNuxtApp } from '#app' + +export function useRequestHeaders (include: K[]): Record; +export function useRequestHeaders (): Readonly>; +export function useRequestHeaders (include?) { + if (process.client) { return {} } + const headers: Record = useNuxtApp().ssrContext?.req.headers ?? {} + if (!include) { return headers } + return Object.fromEntries(include.map(key => [key, headers[key]])) +} diff --git a/packages/nuxt3/src/auto-imports/imports.ts b/packages/nuxt3/src/auto-imports/imports.ts index 792a08978f..1777719eca 100644 --- a/packages/nuxt3/src/auto-imports/imports.ts +++ b/packages/nuxt3/src/auto-imports/imports.ts @@ -14,7 +14,8 @@ export const Nuxt3AutoImports: AutoImportSource[] = [ 'useState', 'useFetch', 'useLazyFetch', - 'useCookie' + 'useCookie', + 'useRequestHeaders' ] }, // #meta diff --git a/packages/nuxt3/test/auto-imports.test.ts b/packages/nuxt3/test/auto-imports.test.ts index 29d38eb3a7..4c390cc051 100644 --- a/packages/nuxt3/test/auto-imports.test.ts +++ b/packages/nuxt3/test/auto-imports.test.ts @@ -1,5 +1,8 @@ +import { readFileSync } from 'fs' import type { AutoImport } from '@nuxt/schema' import { expect } from 'chai' +import { join } from 'pathe' +import { createCommonJS, findExports } from 'mlly' import * as VueFunctions from 'vue' import { AutoImportContext, updateAutoImportContext } from '../src/auto-imports/context' import { TransformPlugin } from '../src/auto-imports/transform' @@ -37,6 +40,27 @@ describe('auto-imports:transform', () => { }) }) +const excludedNuxtHelpers = ['useHydration'] + +describe('auto-imports:nuxt3', () => { + try { + const { __dirname } = createCommonJS(import.meta.url) + const entrypointContents = readFileSync(join(__dirname, '../src/app/composables/index.ts'), 'utf8') + + const names = findExports(entrypointContents).flatMap(i => i.names || i.name) + for (const name of names) { + if (excludedNuxtHelpers.includes(name)) { + continue + } + it(`should register ${name} globally`, () => { + expect(Nuxt3AutoImports.find(a => a.from === '#app').names).to.include(name) + }) + } + } catch (e) { + console.log(e) + } +}) + const excludedVueHelpers = [ 'EffectScope', 'ReactiveEffect',