Skip to content

Commit

Permalink
fix(preview): send configured headers (#9976)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Sep 5, 2022
1 parent 44dbcbe commit 0d20eae
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 2 deletions.
6 changes: 6 additions & 0 deletions docs/config/preview-options.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit 0d20eae

Please sign in to comment.