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

feat: add server.cors config #4183

Merged
merged 2 commits into from
Dec 13, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions e2e/cases/server/cors/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { build, dev } from '@e2e/helper';
import { expect, test } from '@playwright/test';

test('should include CORS headers by default for dev server', async ({
page,
request,
}) => {
const rsbuild = await dev({
cwd: __dirname,
page,
});

const response = await request.get(`http://localhost:${rsbuild.port}`);
expect(response.headers()['access-control-allow-origin']).toEqual('*');

await rsbuild.close();
});

test('should include CORS headers by default for preview server', async ({
page,
request,
}) => {
const rsbuild = await build({
cwd: __dirname,
page,
});

const response = await request.get(`http://localhost:${rsbuild.port}`);
expect(response.headers()['access-control-allow-origin']).toEqual('*');

await rsbuild.close();
});

test('should allow to disable CORS', async ({ page, request }) => {
const rsbuild = await build({
cwd: __dirname,
page,
rsbuildConfig: {
server: {
cors: false,
},
},
});

const response = await request.get(`http://localhost:${rsbuild.port}`);
expect(response.headers()).not.toHaveProperty('access-control-allow-origin');

await rsbuild.close();
});

test('should allow to configure CORS', async ({ page, request }) => {
const rsbuild = await build({
cwd: __dirname,
page,
rsbuildConfig: {
server: {
cors: {
origin: 'https://example.com',
},
},
},
});

const response = await request.get(`http://localhost:${rsbuild.port}`);
expect(response.headers()['access-control-allow-origin']).toEqual(
'https://example.com',
);

await rsbuild.close();
});
1 change: 1 addition & 0 deletions e2e/cases/server/cors/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('Hello Rsbuild!');
1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"commander": "^12.1.0",
"connect": "3.7.0",
"connect-history-api-fallback": "^2.0.0",
"cors": "^2.8.5",
"css-loader": "7.1.2",
"deepmerge": "^4.3.1",
"dotenv": "16.4.7",
Expand Down
1 change: 1 addition & 0 deletions packages/core/prebundle.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export default {
'mrmime',
'tinyglobby',
'chokidar',
'cors',
{
name: 'picocolors',
beforeBundle({ depPath }) {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ const getDefaultServerConfig = (): NormalizedServerConfig => ({
compress: true,
printUrls: true,
strictPort: false,
cors: true,
});

let swcHelpersPath: string;
Expand Down
9 changes: 9 additions & 0 deletions packages/core/src/server/getDevMiddlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,15 @@ const applyDefaultMiddlewares = async ({
next();
});

if (server.cors) {
const { default: corsMiddleware } = await import(
'../../compiled/cors/index.js'
);
middlewares.push(
corsMiddleware(typeof server.cors === 'boolean' ? {} : server.cors),
);
}

// dev proxy handler, each proxy has own handler
if (server.proxy) {
const { middlewares: proxyMiddlewares, upgrade } =
Expand Down
11 changes: 10 additions & 1 deletion packages/core/src/server/prodServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export class RsbuildProdServer {
}

private async applyDefaultMiddlewares() {
const { headers, proxy, historyApiFallback, compress, base } =
const { headers, proxy, historyApiFallback, compress, base, cors } =
this.options.serverConfig;

if (logger.level === 'verbose') {
Expand All @@ -82,6 +82,15 @@ export class RsbuildProdServer {
});
}

if (cors) {
const { default: corsMiddleware } = await import(
'../../compiled/cors/index.js'
);
this.middlewares.use(
corsMiddleware(typeof cors === 'boolean' ? {} : cors),
);
}

if (proxy) {
const { middlewares, upgrade } = await createProxyMiddleware(proxy);

Expand Down
11 changes: 11 additions & 0 deletions packages/core/src/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
rspack,
} from '@rspack/core';
import type { ChokidarOptions } from '../../compiled/chokidar/index.js';
import type cors from '../../compiled/cors/index.js';
import type {
Options as HttpProxyOptions,
Filter as ProxyFilter,
Expand Down Expand Up @@ -384,6 +385,15 @@ export interface ServerConfig {
target?: string | string[];
before?: () => Promise<void> | void;
};
/**
* Configure CORS for the dev server or preview server.
* - true: enable CORS with default options.
* - false: disable CORS.
* - object: enable CORS with the specified options.
* @default true
* @link https://github.com/expressjs/cors
*/
cors?: boolean | cors.CorsOptions;
/**
* Configure proxy rules for the dev server or preview server to proxy requests to the specified service.
*/
Expand All @@ -410,6 +420,7 @@ export type NormalizedServerConfig = ServerConfig &
| 'printUrls'
| 'open'
| 'base'
| 'cors'
>
>;

Expand Down
9 changes: 9 additions & 0 deletions packages/core/tests/__snapshots__/environments.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ exports[`environment config > should normalize environment config correctly 1`]
"server": {
"base": "/",
"compress": true,
"cors": true,
"host": "0.0.0.0",
"htmlFallback": "index",
"open": false,
Expand Down Expand Up @@ -253,6 +254,7 @@ exports[`environment config > should normalize environment config correctly 2`]
"server": {
"base": "/",
"compress": true,
"cors": true,
"host": "0.0.0.0",
"htmlFallback": "index",
"open": false,
Expand Down Expand Up @@ -394,6 +396,7 @@ exports[`environment config > should print environment config when inspect confi
"server": {
"base": "/",
"compress": true,
"cors": true,
"host": "0.0.0.0",
"htmlFallback": "index",
"open": false,
Expand Down Expand Up @@ -531,6 +534,7 @@ exports[`environment config > should print environment config when inspect confi
"server": {
"base": "/",
"compress": true,
"cors": true,
"host": "0.0.0.0",
"htmlFallback": "index",
"open": false,
Expand Down Expand Up @@ -688,6 +692,7 @@ exports[`environment config > should support modify environment config by api.mo
"server": {
"base": "/",
"compress": true,
"cors": true,
"host": "0.0.0.0",
"htmlFallback": "index",
"open": false,
Expand Down Expand Up @@ -826,6 +831,7 @@ exports[`environment config > should support modify environment config by api.mo
"server": {
"base": "/",
"compress": true,
"cors": true,
"host": "0.0.0.0",
"htmlFallback": "index",
"open": false,
Expand Down Expand Up @@ -964,6 +970,7 @@ exports[`environment config > should support modify environment config by api.mo
"server": {
"base": "/",
"compress": true,
"cors": true,
"host": "0.0.0.0",
"htmlFallback": "index",
"open": false,
Expand Down Expand Up @@ -1104,6 +1111,7 @@ exports[`environment config > should support modify single environment config by
"server": {
"base": "/",
"compress": true,
"cors": true,
"host": "0.0.0.0",
"htmlFallback": "index",
"open": false,
Expand Down Expand Up @@ -1242,6 +1250,7 @@ exports[`environment config > should support modify single environment config by
"server": {
"base": "/",
"compress": true,
"cors": true,
"host": "0.0.0.0",
"htmlFallback": "index",
"open": false,
Expand Down
12 changes: 12 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading