Skip to content

Commit 0d20eae

Browse files
authored
fix(preview): send configured headers (#9976)
1 parent 44dbcbe commit 0d20eae

File tree

5 files changed

+33
-2
lines changed

5 files changed

+33
-2
lines changed

docs/config/preview-options.md

+6
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,9 @@ Uses [`http-proxy`](https://github.com/http-party/node-http-proxy). Full options
7575
- **Default:** [`server.cors`](./server-options#server-cors)
7676

7777
Configure CORS for the preview server. This is enabled by default and allows any origin. Pass an [options object](https://github.com/expressjs/cors) to fine tune the behavior or `false` to disable.
78+
79+
## preview.headers
80+
81+
- **Type:** `OutgoingHttpHeaders`
82+
83+
Specify server response headers.

packages/vite/src/node/preview.ts

+9-1
Original file line numberDiff line numberDiff line change
@@ -111,12 +111,20 @@ export async function preview(
111111

112112
// static assets
113113
const distDir = path.resolve(config.root, config.build.outDir)
114+
const headers = config.preview.headers
114115
app.use(
115116
previewBase,
116117
sirv(distDir, {
117118
etag: true,
118119
dev: true,
119-
single: config.appType === 'spa'
120+
single: config.appType === 'spa',
121+
setHeaders(res) {
122+
if (headers) {
123+
for (const name in headers) {
124+
res.setHeader(name, headers[name]!)
125+
}
126+
}
127+
}
120128
})
121129
)
122130

playground/fs-serve/__tests__/fs-serve.spec.ts

+9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import fetch from 'node-fetch'
12
import { beforeAll, describe, expect, test } from 'vitest'
23
import testJSON from '../safe.json'
34
import { isServe, page, viteTestUrl } from '~utils'
@@ -97,3 +98,11 @@ describe.runIf(isServe)('main', () => {
9798
expect(await page.textContent('.unsafe-dotenv')).toBe('404')
9899
})
99100
})
101+
102+
describe('fetch', () => {
103+
// Note: this should pass in build too, but the test setup doesn't use Vite preview
104+
test.runIf(isServe)('serve with configured headers', async () => {
105+
const res = await fetch(viteTestUrl + '/src/')
106+
expect(res.headers.get('x-served-by')).toBe('vite')
107+
})
108+
})

playground/fs-serve/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,6 @@
66
"dev": "vite root",
77
"build": "vite build root",
88
"debug": "node --inspect-brk ../../packages/vite/bin/vite",
9-
"preview": "vite preview"
9+
"preview": "vite preview root"
1010
}
1111
}

playground/fs-serve/root/vite.config.js

+8
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@ module.exports = {
1818
},
1919
hmr: {
2020
overlay: false
21+
},
22+
headers: {
23+
'x-served-by': 'vite'
24+
}
25+
},
26+
preview: {
27+
headers: {
28+
'x-served-by': 'vite'
2129
}
2230
},
2331
define: {

0 commit comments

Comments
 (0)