Skip to content

Instantly share code, notes, and snippets.

@benlongo
Created February 28, 2025 19:38
Show Gist options
  • Save benlongo/dee06ed8acbd4e04f6e718b9bef63cbc to your computer and use it in GitHub Desktop.
Save benlongo/dee06ed8acbd4e04f6e718b9bef63cbc to your computer and use it in GitHub Desktop.
import child_process from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import type { Plugin, ResolvedConfig } from 'vite';
/**
* Vite plugin to generate and configure HTTPS certificates from dotnet
*
* Add ./local-certs to your .gitignore
*/
export default function viteDotnetHttps(): Plugin {
const certFileName = 'vite-app';
const certDir = './local-certs';
return {
name: 'vite-plugin-https-dotnet',
configResolved(config: ResolvedConfig) {
if (config.command !== 'serve') return;
const resolvedCertDir = path.resolve(certDir);
const certFilePath = path.join(resolvedCertDir, `${certFileName}.pem`);
const keyFilePath = path.join(resolvedCertDir, `${certFileName}.key`);
try {
// Create certificate directory if needed
if (!fs.existsSync(resolvedCertDir)) {
fs.mkdirSync(resolvedCertDir, { recursive: true });
}
// Only generate certificates if they don't exist
// This avoids prompting for keychain access if certificates are already valid
if (!fs.existsSync(certFilePath) || !fs.existsSync(keyFilePath)) {
console.log('Generating HTTPS certificates for development...');
const result = child_process.spawnSync(
'dotnet',
[
'dev-certs',
'https',
'--export-path',
certFilePath,
'--format',
'Pem',
'--no-password',
'--trust',
],
{ stdio: 'inherit' },
);
if (result.status !== 0) {
throw new Error('Could not create certificate.');
}
}
// Configure HTTPS in the resolved config
config.server.https = {
key: fs.readFileSync(keyFilePath),
cert: fs.readFileSync(certFilePath),
};
} catch (error) {
console.warn('Failed to set up HTTPS:', error);
}
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment