Skip to content

Instantly share code, notes, and snippets.

@stevebauman
Last active May 8, 2025 01:08
Show Gist options
  • Save stevebauman/19662301db6ef67e27f1cf5ad4f43579 to your computer and use it in GitHub Desktop.
Save stevebauman/19662301db6ef67e27f1cf5ad4f43579 to your computer and use it in GitHub Desktop.
Vite Server Cors Allow Any Subdomain
import { defineConfig, loadEnv } from 'vite';
// ...
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd());
const { protocol, hostname } = new URL(env.VITE_URL);
const root = hostname.split('.').slice(-2).join('\\.');
return {
// ...
server: {
cors: {
origin: new RegExp([
'^', // Start of string
`${protocol}//`, // Protocol and double slashes
'(?:[\\w-]+\\.)*', // Optional subdomains
`${root}`, // Root domain (e.g., example.com)
'(?::\\d+)?', // Optional port
'$', // End of string
].join(''), 'i'),
},
},
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment