Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(preview): send configured headers #9976

Merged
merged 2 commits into from Sep 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/config/preview-options.md
Expand Up @@ -75,3 +75,9 @@ Uses [`http-proxy`](https://github.com/http-party/node-http-proxy). Full options
- **Default:** [`server.cors`](./server-options#server-cors)

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.

## preview.headers

- **Type:** `OutgoingHttpHeaders`

Specify server response headers.
10 changes: 9 additions & 1 deletion packages/vite/src/node/preview.ts
Expand Up @@ -111,12 +111,20 @@ export async function preview(

// static assets
const distDir = path.resolve(config.root, config.build.outDir)
const headers = config.preview.headers
app.use(
previewBase,
sirv(distDir, {
etag: true,
dev: true,
single: config.appType === 'spa'
single: config.appType === 'spa',
setHeaders(res) {
if (headers) {
for (const name in headers) {
res.setHeader(name, headers[name]!)
}
}
}
})
)

Expand Down
9 changes: 9 additions & 0 deletions playground/fs-serve/__tests__/fs-serve.spec.ts
@@ -1,3 +1,4 @@
import fetch from 'node-fetch'
import { beforeAll, describe, expect, test } from 'vitest'
import testJSON from '../safe.json'
import { isServe, page, viteTestUrl } from '~utils'
Expand Down Expand Up @@ -97,3 +98,11 @@ describe.runIf(isServe)('main', () => {
expect(await page.textContent('.unsafe-dotenv')).toBe('404')
})
})

describe('fetch', () => {
// Note: this should pass in build too, but the test setup doesn't use Vite preview
test.runIf(isServe)('serve with configured headers', async () => {
const res = await fetch(viteTestUrl + '/src/')
expect(res.headers.get('x-served-by')).toBe('vite')
})
})
2 changes: 1 addition & 1 deletion playground/fs-serve/package.json
Expand Up @@ -6,6 +6,6 @@
"dev": "vite root",
"build": "vite build root",
"debug": "node --inspect-brk ../../packages/vite/bin/vite",
"preview": "vite preview"
"preview": "vite preview root"
}
}
8 changes: 8 additions & 0 deletions playground/fs-serve/root/vite.config.js
Expand Up @@ -18,6 +18,14 @@ module.exports = {
},
hmr: {
overlay: false
},
headers: {
'x-served-by': 'vite'
}
},
preview: {
headers: {
'x-served-by': 'vite'
}
},
define: {
Expand Down