### Basic HTTPS Setup Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/usage-patterns.md Enables HTTPS for the development server by generating and caching a certificate. Start the dev server normally after applying this configuration. ```typescript import { defineConfig } from 'vite' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [basicSsl()] }) ``` ```bash npm run dev # or vite ``` -------------------------------- ### Start Development Server Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md Start your development server with the configured SSL. The dev server will run on HTTPS with an auto-generated self-signed certificate. ```bash npm run dev ``` -------------------------------- ### Install vite-plugin-basic-ssl Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md Install the plugin using npm. ```bash npm install @vitejs/plugin-basic-ssl ``` -------------------------------- ### Start Express Backend and Vite Frontend Servers Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Commands to start both the Express backend and the Vite frontend development server simultaneously. This is necessary for the proxy configuration to work correctly. ```bash # Terminal 1: Backend npx ts-node server.ts # Terminal 2: Frontend npm run dev ``` -------------------------------- ### TypeScript Import Example Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/module-structure.md How to import the plugin, its types, and named exports in a TypeScript environment. ```typescript import basicSsl from '@vitejs/plugin-basic-ssl' import type { Options } from '@vitejs/plugin-basic-ssl' import { getCertificate } from '@vitejs/plugin-basic-ssl' ``` -------------------------------- ### Initialization Data Flow Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/implementation-overview.md Describes the sequence of events from Vite starting to the dev server being configured with HTTPS certificates. ```mermaid graph TD Vite starts ↓ viteBasicSslPlugin() called ↓ Plugin object created { name, configResolved hook } ↓ Vite resolves configuration ↓ configResolved() hook invoked ↓ getCertificate(cacheDir, name, domains, ttlDays) ├─ Check cache: read {cacheDir}/_cert.pem │ ├─ If exists and valid → return (cache hit) │ └─ If missing or expired → generate new │ └─ dynamic import('./certificate') │ └─ createCertificate(name, domains, ttlDays) │ ├─ Generate 2048-bit RSA key pair │ ├─ Create X.509 certificate │ ├─ Sign with SHA-256 │ └─ Return PEM string └─ Write cache asynchronously (fire & forget) ↓ Set config.server.https = { cert, key } Set config.preview.https = { cert, key } ↓ Vite starts dev server with HTTPS ``` -------------------------------- ### Key Usage Example Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/certificate-generation-details.md Defines the permitted uses for the certificate, including signing, encryption, and non-repudiation. ```text keyUsage = keyCertSign, digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment ``` -------------------------------- ### Accessing React Dev Server with Basic SSL Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Instructions on how to start the React development server and access it via HTTPS. Acknowledge the browser security warning. ```bash npm run dev # Server starts at https://localhost:5173 ``` -------------------------------- ### Output Format Example Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/certificate-generation-details.md Shows the concatenated PEM string format of the output, containing the RSA private key and the X.509 certificate. ```text [RSA Private Key in PKCS#1 format] [X.509 Certificate in DER, base64-encoded] ``` -------------------------------- ### Install npm/yarn Packages with Insecure Flag Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/certificate-generation-details.md Command to install npm or yarn packages while bypassing TLS certificate verification, useful in environments with self-signed certificates. ```bash npm install --insecure ``` -------------------------------- ### CommonJS Import Example Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/module-structure.md How to import the plugin and its named exports using CommonJS 'require'. ```typescript const basicSsl = require('@vitejs/plugin-basic-ssl') const { getCertificate } = require('@vitejs/plugin-basic-ssl') ``` -------------------------------- ### User-Provided SAN Entries Example Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/certificate-generation-details.md Demonstrates how user-provided domains are added to the Subject Alternative Name (SAN) extension as DNS records. ```typescript domains: ['*.dev.local', 'myapp.com', 'api.example.com'] ``` -------------------------------- ### Configure Vite with Basic SSL Plugin Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/api-reference-vite-plugin.md Example of how to integrate the basicSsl plugin into your vite.config.ts file. It shows how to pass custom options for certificate generation and specify the server port. ```typescript import { defineConfig } from 'vite' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [ basicSsl({ name: 'myapp', domains: ['localhost', '*.dev.local'], ttlDays: 60, certDir: '/tmp/certs' }) ], server: { port: 443 } }) ``` -------------------------------- ### ES Modules Import Example Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/module-structure.md How to import the plugin and its named exports using ES Modules 'import'. ```typescript import basicSsl from '@vitejs/plugin-basic-ssl' import { getCertificate } from '@vitejs/plugin-basic-ssl' ``` -------------------------------- ### Bash Commands for Cypress Integration Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Commands to start the Vite dev server and run Cypress tests concurrently. Ensure the dev server is running before executing Cypress. ```bash # Terminal 1: Start dev server npm run dev # Terminal 2: Run Cypress npx cypress run ``` -------------------------------- ### Merged HTTPS Configuration Example Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/configuration.md Illustrates the resulting HTTPS configuration object after vite-plugin-basic-ssl merges its generated certificate and key with custom user-provided options. ```typescript { spdy: { plain: false }, cert: '-----BEGIN RSA PRIVATE KEY-----...', key: '-----BEGIN RSA PRIVATE KEY-----...' } ``` -------------------------------- ### Example: Custom Middleware with HTTPS Configuration Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/configuration.md Demonstrates how to use vite-plugin-basic-ssl with custom server HTTPS options. The plugin merges its certificate and key into the provided HTTPS object, preserving other configurations like 'spdy'. ```typescript import https from 'node:https' export default defineConfig({ plugins: [basicSsl()], server: { https: { // Custom middleware or options spdy: { plain: false } }, middlewareMode: false } }) ``` -------------------------------- ### Dockerfile for Vite Development Container Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md A Dockerfile to set up a development environment for a Vite application. It installs dependencies, copies source code, and starts the dev server with HTTPS. ```dockerfile FROM node:22-alpine WORKDIR /app # Install dependencies COPY package*.json . RUN npm install # Copy source COPY . . # Pre-generate certificate (optional) ARG CERT_DOMAINS=localhost RUN npm run build # Expose dev server port EXPOSE 5173 # Start dev server with HTTPS CMD ["npm", "run", "dev"] ``` -------------------------------- ### Configuration Modification Example Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/implementation-overview.md Shows how the plugin modifies the Vite configuration object in-place, preserving existing HTTPS options and adding certificate and key. ```typescript // Before plugin config.server.https = undefined || { someOption: true } config.preview.https = false // After plugin config.server.https = { someOption: true, // Preserved via Object.assign cert: certificateContent, key: certificateContent } config.preview.https = false // Unchanged (explicit false is respected) ``` -------------------------------- ### Extended Key Usage Example Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/certificate-generation-details.md Specifies the purposes for which the certificate is valid, such as server authentication and client authentication. ```text extKeyUsage = serverAuth, clientAuth, codeSigning, timeStamping ``` -------------------------------- ### Dockerfile for Production Static Serving Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md A Dockerfile to build and serve a static Vite application over HTTPS using a self-signed certificate. It installs `serve` and runs the built app. ```dockerfile FROM node:22-alpine WORKDIR /app # Build app COPY package*.json . RUN npm install COPY . . RUN npm run build # Serve with HTTPS FROM node:22-alpine WORKDIR /app RUN npm install -g serve COPY --from=0 /app/dist ./ EXPOSE 3000 # Serve dist folder over HTTPS with self-signed cert CMD ["node", "-e", "\ const fs = require('fs'), https = require('https'), path = require('path'); \ const dir = process.cwd(); \ const { createCertificate } = require('@vitejs/plugin-basic-ssl'); \ (async () => { \ const cert = await createCertificate('prod'); \ const server = https.createServer({ cert, key: cert }, (req, res) => { \ const file = path.join(dir, req.url === '/' ? 'index.html' : req.url); \ if (fs.existsSync(file)) fs.createReadStream(file).pipe(res); \ else res.writeHead(404).end(); \ }); \ server.listen(3000); \ })() \ "] ``` -------------------------------- ### Docker Development Container Setup Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/usage-patterns.md Integrates vite-plugin-basic-ssl into a Dockerized development environment, persisting certificates in a Docker volume to avoid regeneration on container restarts. The Vite server is configured to listen on all interfaces. ```dockerfile FROM node:22 WORKDIR /app COPY package.json package-lock.json ./ RUN npm install # Pre-generate certificate during build (optional) RUN npm run gen-cert 2>/dev/null || true COPY . . EXPOSE 5173 CMD ["npm", "run", "dev"] ``` ```typescript import { defineConfig } from 'vite' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [ basicSsl({ certDir: '/app/.dev-certs' }) ], server: { host: '0.0.0.0', // Listen on all interfaces port: 5173 } }) ``` ```yaml version: '3' services: app: build: . ports: - "5173:5173" volumes: - .:/app - /app/node_modules - dev-certs:/app/.dev-certs # Persist certs volumes: dev-certs: ``` ```bash curl --insecure https://localhost:5173 ``` -------------------------------- ### Enable HTTPS during Development Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md Use this snippet to quickly enable HTTPS for your development server without manual certificate setup. ```typescript basicSsl() ``` -------------------------------- ### Subject Distinguished Name (DN) Example Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/certificate-generation-details.md Specifies the attributes for the certificate's subject distinguished name. Defaults to 'example.org' for the Common Name. ```text CN=example.org,C=US,ST=Virginia,L=Blacksburg,O=Test,OU=Test ``` -------------------------------- ### Use Certificate with Node.js HTTPS Server Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/api-reference-certificate.md Configures and starts a Node.js HTTPS server using the generated certificate and private key. ```typescript // Use with Node.js HTTPS server import https from 'node:https' const server = https.createServer({ cert: cert2, key: cert2 }, (req, res) => { res.end('Hello HTTPS') }) server.listen(443) ``` -------------------------------- ### Graceful Degradation Strategy Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/implementation-overview.md Outlines the plugin's fail-open strategy for handling certificate generation and cache write/read failures to ensure the dev server starts. ```plaintext If certificate generation fails → Return partial/default certificate → Log error (optional) → Continue operation If cache write fails → Ignore failure → Certificate already returned to Vite → Dev server still runs If cache read fails → Treat as cache miss → Generate new certificate → Try to write cache (ignore if it fails) ``` -------------------------------- ### Commented-Out Basic Constraints Extension Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/certificate-generation-details.md An example of a commented-out basicConstraints extension. If enabled with 'cA: true', it would mark the certificate as a Certificate Authority. ```typescript // { // name: 'basicConstraints', // cA: true, // } ``` -------------------------------- ### Certificate Expiration Check Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/types.md Example of using X509Certificate to check if a certificate has expired. It parses the certificate content and compares the expiration date with the current date. ```typescript import { X509Certificate } from 'node:crypto' export function isCertificateExpired(content: string): boolean { const cert = new X509Certificate(content) const expirationDate = getCertificateExpirationDate(cert) return new Date() > expirationDate } ``` -------------------------------- ### Build Process Visualization Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/implementation-overview.md Illustrates the build pipeline using unbuild, showing the transformation from TypeScript source files to various distribution formats (CommonJS, ES Module, TypeScript definitions). ```text src/index.ts src/certificate.ts src/certificate-expiration.ts ↓ TypeScript compiler package.json {exports, main, module, types} ↓ unbuild dist/index.cjs (CommonJS) dist/index.mjs (ES Module) dist/index.d.ts (TypeScript definitions) ``` -------------------------------- ### Certificate Generation Algorithm Steps Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/implementation-overview.md Outlines the algorithm used by `createCertificate` to generate RSA keys, X.509 certificates, and PEM encoded outputs. ```plaintext Input: name (default 'example.org'), domains (optional), ttlDays (default 30) Step 1: Prepare extensions - Create keyUsage extension (keyCertSign, digitalSignature, etc.) - Create extKeyUsage extension (serverAuth, clientAuth, etc.) - Create subjectAltName extension with base domains + user domains Step 2: Prepare certificate subject attributes CN=name, C=US, ST=Virginia, L=Blacksburg, O=Test, OU=Test Step 3: Generate RSA key pair keySize = 2048 bits keyPair = forge.pki.rsa.generateKeyPair(2048) Step 4: Create certificate cert = forge.pki.createCertificate() Step 5: Set serial number Generate 9 random bytes Convert to hex string Apply toPositiveHex() to ensure RFC 5280 compliance cert.serialNumber = result Step 6: Set validity period cert.validity.notBefore = new Date() cert.validity.notAfter = new Date() + ttlDays days Step 7: Set subject and issuer (self-signed) cert.setSubject(attributes) cert.setIssuer(attributes) Step 8: Set public key cert.publicKey = keyPair.publicKey Step 9: Set extensions cert.setExtensions(extensions) Step 10: Sign certificate algorithm = forge.md.sha256.create() cert.sign(keyPair.privateKey, algorithm) Step 11: Encode outputs privateKeyPem = forge.pki.privateKeyToPem(keyPair.privateKey) certPem = forge.pki.certificateToPem(cert) Step 12: Concatenate and return return privateKeyPem + certPem ``` -------------------------------- ### Configure Proxy for Backend Connection Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Use this configuration to set up a proxy for your backend API. Ensure the target URL matches your backend port. Set `rejectUnauthorized` to `false` if using self-signed certificates. ```typescript server: { proxy: { '/api': { target: 'https://localhost:3000', // Match your backend port changeOrigin: true, rejectUnauthorized: false // For self-signed certs } } } ``` -------------------------------- ### Regenerate Certificate by Deleting Cache Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md If the certificate has expired or is causing issues, remove the cached certificate file to force regeneration on the next server start. ```bash rm node_modules/.vite/basic-ssl/_cert.pem npm run dev # Regenerates certificate ``` -------------------------------- ### Vite Config: Ensure Plugin is Loaded Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Troubleshooting step to ensure the basicSsl plugin is correctly added to the Vite configuration. The plugin must be present in the `plugins` array. ```typescript export default defineConfig({ plugins: [basicSsl()] // Must be before other plugins }) ``` -------------------------------- ### Vite Plugin Object Creation Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/implementation-overview.md Illustrates the initial phase of the plugin's lifecycle where the plugin object is created and returned. ```javascript viteBasicSslPlugin(options) Returns: { name: 'vite:basic-ssl', configResolved: ... } ``` -------------------------------- ### Apply SSL Certificate to Server and Preview Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/configuration.md This logic handles the application of generated SSL certificates to both the Vite development server and the preview server. It merges the certificate and key into existing HTTPS configurations or applies them if HTTPS is not explicitly set. ```typescript async configResolved(config) { const certificate = await getCertificate( options?.certDir ?? (config.cacheDir ?? defaultCacheDir) + '/basic-ssl', options?.name, options?.domains, options?.ttlDays, ) const https = () => ({ cert: certificate, key: certificate }) // Apply to server if not explicitly disabled if (config.server.https === undefined || !!config.server.https) { config.server.https = Object.assign({}, config.server.https, https()) } // Apply to preview if not explicitly disabled if (config.preview.https === undefined || !!config.preview.https) { config.preview.https = Object.assign({}, config.preview.https, https()) } } ``` -------------------------------- ### Environment-Specific Configuration with .env files Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/usage-patterns.md Manage certificate name, domains, and TTL using environment variables loaded from .env files. This allows different configurations for development, staging, or production environments. ```typescript import { defineConfig, loadEnv } from 'vite' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig(({ command, mode }) => { const env = loadEnv(mode, process.cwd(), 'VITE_') const domains = env.VITE_CERT_DOMAINS?.split(',') || ['localhost'] return { plugins: [ basicSsl({ name: env.VITE_CERT_NAME || 'app', domains, ttlDays: parseInt(env.VITE_CERT_TTL || '30') }) ] } }) ``` ```dotenv VITE_CERT_NAME=app-dev VITE_CERT_DOMAINS=localhost,*.dev,api.dev VITE_CERT_TTL=30 ``` ```dotenv VITE_CERT_NAME=app-staging VITE_CERT_DOMAINS=localhost,*.staging,api.staging VITE_CERT_TTL=60 ``` ```bash vite --mode development vite --mode staging ``` -------------------------------- ### Configure Vite for Basic SSL Plugin Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md Ensure the `basicSsl` plugin is included in your Vite configuration's `plugins` array and that `server.https` is not explicitly set to `false` to enable HTTPS. ```typescript export default defineConfig({ plugins: [basicSsl()], server: { // Don't set https: false } }) ``` -------------------------------- ### Module Hierarchy Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/implementation-overview.md Illustrates the main modules and their relationships within the plugin's source code. ```tree src/index.ts (plugin entry point) ├── viteBasicSslPlugin() ├── getCertificate() │ ├── (cached cert read path) │ └── dynamic import → src/certificate.ts │ └── createCertificate() │ └── node-forge RSA & X.509 APIs │ └── dependency on src/certificate-expiration.ts ├── isCertificateExpired() └── parseNonStandardDateString() ``` -------------------------------- ### Inspect Certificate Details Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md Use openssl commands to view the details and expiration dates of the generated certificate. ```bash # View certificate details openssl x509 -in node_modules/.vite/basic-ssl/_cert.pem -text -noout ``` ```bash # Check expiration openssl x509 -in node_modules/.vite/basic-ssl/_cert.pem -noout -dates ``` -------------------------------- ### Vite Proxy Configuration for HTTPS Backend with Self-Signed Certificates Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Configure Vite's server proxy to communicate with an HTTPS backend that uses self-signed certificates. The `agent` option with `rejectUnauthorized: false` is crucial for this setup. ```typescript import https from 'node:https' export default defineConfig({ plugins: [basicSsl()], server: { https: true, proxy: { '/api': { target: 'https://localhost:3000', changeOrigin: true, agent: new https.Agent({ rejectUnauthorized: false // Accept self-signed certs }) } } } }) ``` -------------------------------- ### Importing Named Export Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/module-structure.md Demonstrates how to import the 'getCertificate' named export directly from the plugin. ```typescript import { getCertificate } from '@vitejs/plugin-basic-ssl' ``` -------------------------------- ### Node.js HTTPS Server with PEM Content Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/types.md Demonstrates how to create a Node.js HTTPS server using PEM content for both certificate and key. This is useful when the PEM file contains both the private key and the certificate. ```typescript import https from 'node:https' const options = { cert: pemContent, // Can include both private key and certificate key: pemContent // Can be the same as cert } https.createServer(options, (req, res) => { res.end('Hello') }).listen(443) ``` -------------------------------- ### Signing Certificate with SHA-256 Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/certificate-generation-details.md Demonstrates signing an X.509 certificate using the SHA-256 hash algorithm with forge.js. ```typescript const algorithm = forge.md.sha256.create() cert.sign(keyPair.privateKey, algorithm) ``` -------------------------------- ### Generate Certificate for CI/Docker Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Pre-generate the SSL certificate in CI or Docker environments to avoid delays during development server startup. This ensures the certificate is cached for subsequent runs. ```bash # Generate certificate once npm run build # Then run dev server (uses cached cert) npm run dev ``` ```dockerfile RUN npm install && npm run build # Generates cert during build CMD ["npm", "run", "dev"] # Reuses cached cert ``` -------------------------------- ### Configure Custom Domains for HTTPS Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md Supports multiple domain names and wildcard patterns for HTTPS. Ensure your DNS or hosts file is updated accordingly. ```typescript basicSsl({ name: 'myapp.local', domains: ['*.myapp.local', 'api.myapp.local'] }) ``` -------------------------------- ### Import vite-plugin-basic-ssl using named default export Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/api-reference-vite-plugin.md This import syntax is equivalent to the default export pattern and can also be used to include the plugin. ```typescript import { default as basicSsl } from '@vitejs/plugin-basic-ssl' ``` -------------------------------- ### Plugin Options Interface Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/configuration.md Defines the available configuration options for customizing certificate generation and caching. Options include custom cache directory, additional domains, certificate name, and validity period. ```typescript interface Options { certDir?: string // Custom certificate cache directory domains?: string[] // Additional domain names for the certificate name?: string // Certificate Common Name ttlDays?: number // Certificate validity period in days } ``` -------------------------------- ### Plugin Options Interface Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/types.md Defines the configuration options for the viteBasicSslPlugin. Fields can be omitted as the plugin provides default values. ```typescript interface Options { certDir: string domains: string[] name: string ttlDays: number } ``` -------------------------------- ### Multiple Domains with Wildcard Support Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/usage-patterns.md Generates a certificate that covers multiple specific subdomains and wildcard domains, simplifying certificate management for complex applications. Includes default loopback addresses. ```typescript const domains = [ 'localhost', '*.dev', '*.app.dev', 'api.dev', 'admin.dev', 'www.dev' ] export default defineConfig({ plugins: [ basicSsl({ name: 'dev', domains }) ] }) ``` -------------------------------- ### Docker Compose for Development Environment Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Docker Compose configuration to build and run a Vite development container. It maps ports, sets up volumes for code and certificates, and defines environment variables. ```yaml version: '3.8' services: app: build: context: . args: CERT_DOMAINS: localhost,app.local,api.local ports: - "5173:5173" volumes: - .:/app - /app/node_modules - certs:/app/node_modules/.vite/basic-ssl environment: - NODE_ENV=development volumes: certs: ``` -------------------------------- ### Basic vite.config.ts Configuration Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md Configure the plugin in your vite.config.ts file to enable basic SSL for your development server. ```typescript import { defineConfig } from 'vite' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [basicSsl()] }) ``` -------------------------------- ### Vite Config: Add Custom Domains Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Configure the basicSsl plugin to include custom domains for the self-signed certificate. This helps avoid domain mismatch warnings in the browser. ```typescript basicSsl({ domains: ['myapp.local', '*.myapp.local'] }) ``` -------------------------------- ### Minimal Vite Configuration Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/configuration.md Uses all default settings for the vite-plugin-basic-ssl. This configuration is suitable for basic local development without custom domain names or cache directories. ```typescript // vite.config.ts import { defineConfig } from 'vite' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [basicSsl()] }) ``` -------------------------------- ### Configure Vite with basic-ssl Plugin Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/README.md Integrate the basic-ssl plugin into your vite.config.js. Customize certificate name, trusted domains, expiration, and certification directory. ```js import basicSsl from '@vitejs/plugin-basic-ssl' export default { plugins: [ basicSsl({ /** name of certification */ name: 'test', /** custom trust domains */ domains: ['*.custom.com'], /** optional, days before certificate expires */ ttlDays: 30, /** custom certification directory */ certDir: '/Users/.../.devServer/cert', }), ], } ``` -------------------------------- ### Import vite-plugin-basic-ssl using default export Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/api-reference-vite-plugin.md Use this common import pattern to include the vite-plugin-basic-ssl in your Vite project. ```typescript import basicSsl from '@vitejs/plugin-basic-ssl' ``` -------------------------------- ### Custom Domain Names and TTL Configuration Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/configuration.md Configures the plugin with custom domain names, including wildcard patterns and IP addresses, and sets a longer certificate validity period. This is useful for development environments with specific hostnames or when longer certificate lifespans are desired. ```typescript export default defineConfig({ plugins: [ basicSsl({ name: 'localhost', domains: ['localhost', '*.dev.local', '192.168.1.100'], ttlDays: 365 }) ] }) ``` -------------------------------- ### Retrieve or Generate HTTPS Certificate Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/api-reference-vite-plugin.md Demonstrates how to use the getCertificate function to obtain a PEM-encoded HTTPS certificate. This includes specifying cache directory, certificate name, additional domains, and validity period. ```typescript import { getCertificate } from '@vitejs/plugin-basic-ssl' const certPem = await getCertificate( '/home/user/.devServer/certs', 'localhost', ['*.example.com'], 90 ) // Use certPem with your HTTPS server const https = { cert: certPem, key: certPem } ``` -------------------------------- ### CI/CD Integration: Custom Certificate Directory Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/usage-patterns.md Configure a temporary directory for certificates in CI environments to avoid persistence issues. For local development, it uses the default node_modules path. ```typescript // vite.config.ts import { defineConfig } from 'vite' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [ basicSsl({ name: 'ci', certDir: process.env.CI ? '/tmp/ci-certs' // Use temp directory in CI : 'node_modules/.vite/basic-ssl' // Persist in local dev }) ] }) ``` -------------------------------- ### Custom Domain Configuration Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/usage-patterns.md Generates a certificate for specific domain names, useful when your project requires custom hostnames. Ensure your hosts file or DNS is configured accordingly. ```typescript // vite.config.ts import { defineConfig } from 'vite' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [ basicSsl({ name: 'myapp.local', domains: ['localhost', '*.myapp.local', 'api.myapp.local'] }) ], server: { host: 'myapp.local' } }) ``` ```bash # /etc/hosts 127.0.0.1 myapp.local api.myapp.local dev.myapp.local ``` -------------------------------- ### createCertificate Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md Generates a new X.509 certificate with embedded RSA 2048-bit private key. Used internally by `getCertificate()` but exported for direct use. ```APIDOC ## createCertificate ### Description Generates a new X.509 certificate with embedded RSA 2048-bit private key. Used internally by `getCertificate()` but exported for direct use. ### Signature ```typescript export function createCertificate( name?: string, domains?: string[], ttlDays?: number, ): string ``` ### Parameters - **name** (string) - Optional - Certificate Common Name (default: `'example.org'`) - **domains** (string[]) - Optional - Additional domain names - **ttlDays** (number) - Optional - Validity period in days (default: `30`) ### Returns PEM-encoded string (private key + certificate) ``` -------------------------------- ### Create Certificate with Defaults Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/api-reference-certificate.md Generates a self-signed certificate using default values for name, domains, and validity. ```typescript import { createCertificate } from '@vitejs/plugin-basic-ssl' // Basic usage with defaults const cert1 = createCertificate() ``` -------------------------------- ### Setting Vite Cache Directory via Environment Variable Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/configuration.md Demonstrates how to control Vite's cache directory using the VITE_CACHE_DIR environment variable. This affects the default location for the plugin's certificate cache if certDir is not explicitly set. ```bash # Control where Vite stores cache (optional) export VITE_CACHE_DIR=/custom/cache/path ``` -------------------------------- ### Conditional HTTPS Application Logic Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/implementation-overview.md Explains the conditions under which the plugin will apply HTTPS configuration to the server and preview settings. ```plaintext config.server.https === undefined // Not configured by user OR !!config.server.https === true // User set to true or object (but not if === false) // Respects explicit false ``` -------------------------------- ### Configure Vite for React with Basic SSL Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Integrate vite-plugin-basic-ssl into a React project's vite.config.ts. You can optionally provide a name for the certificate. ```typescript import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [ basicSsl({ name: 'react-app' }), react() ] }) ``` -------------------------------- ### createCertificate Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/api-reference-certificate.md Generates a self-signed X.509 certificate with embedded private key, using node-forge. The returned string contains both the private key and the certificate in PEM format. ```APIDOC ## createCertificate ### Description Generates a self-signed X.509 certificate with embedded private key, using node-forge. ### Function Signature ```typescript export function createCertificate( name: string = 'example.org', domains?: string[], ttlDays: number = 30, ): string ``` ### Parameters #### Path Parameters * **name** (string) - Optional - The Common Name (CN) attribute in the certificate subject. Typically the primary domain name. Defaults to 'example.org'. * **domains** (string[]) - Optional - Additional domain names and wildcards to add to the SubjectAltName extension (e.g., `['*.dev.local', 'test.local']`). Appended after localhost, [::1], 127.0.0.1, and fe80::1. * **ttlDays** (number) - Optional - Number of days the certificate is valid from issuance until expiration. Defaults to 30. ### Return Type `string` - PEM-encoded certificate and private key, concatenated as: `{private-key-pem}{certificate-pem}` ### Behavior Creates a self-signed certificate with the following characteristics: - Key Size: 2048-bit RSA - Signature Algorithm: SHA-256 - Subject: Uses the provided `name` and fixed organizational attributes (Country: US, State: Virginia, Locality: Blacksburg, Organization: Test) - Subject Alternative Names (SubjectAltName): Always includes: DNS: `localhost`, DNS: `[::1]`, IP: `127.0.0.1`, IP: `fe80::1` (IPv6 link-local), Plus any additional domains passed in the `domains` parameter - Key Usage: keyCertSign, digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment - Extended Key Usage: serverAuth, clientAuth, codeSigning, timeStamping - Serial Number: Randomly generated 9-byte value, converted to positive hex representation (RFC 5280 compliance) - Issuer: Identical to Subject (self-signed) ### Usage Example ```typescript import { createCertificate } from '@vitejs/plugin-basic-ssl' // Basic usage with defaults const cert1 = createCertificate() // With custom domain and name const cert2 = createCertificate( 'myapp.local', ['*.myapp.local', 'api.myapp.local'], 60 // valid for 60 days ) // Write to file import fs from 'node:fs' fs.writeFileSync('cert.pem', cert2) // Use with Node.js HTTPS server import https from 'node:https' const server = https.createServer({ cert: cert2, key: cert2 }, (req, res) => { res.end('Hello HTTPS') }) server.listen(443) ``` ``` -------------------------------- ### Vite Config: Avoid Disabling HTTPS Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Troubleshooting step to prevent accidental disabling of HTTPS. Ensure `server.https` is not set to `false`, as this overrides the basicSsl plugin's configuration. ```typescript export default defineConfig({ plugins: [basicSsl()], // DON'T do this: server: { https: false // Disables plugin's HTTPS config } }) ``` -------------------------------- ### Configure Vite Frontend Proxy for Express Backend Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Set up Vite's proxy in vite.config.ts to forward API requests to an Express backend running on HTTPS. Ensure `rejectUnauthorized` is set to false for self-signed certificates. ```typescript import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [basicSsl(), vue()], server: { port: 5173, proxy: { '/api': { target: 'https://localhost:3000', changeOrigin: true, rejectUnauthorized: false // Allow self-signed certs } } } }) ``` -------------------------------- ### Configure Vite for Vue 3 with Basic SSL Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Integrate vite-plugin-basic-ssl into a Vue 3 project's vite.config.ts. Ensure the plugin is included in the plugins array. ```typescript import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [ basicSsl(), vue() ] }) ``` -------------------------------- ### Inspect Cached Certificate with OpenSSL Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/certificate-generation-details.md Command to inspect the details of a cached PEM certificate using OpenSSL. ```bash openssl x509 -in node_modules/.vite/basic-ssl/_cert.pem -text -noout ``` -------------------------------- ### Configure Vite for Svelte with Basic SSL Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Integrate vite-plugin-basic-ssl into a Svelte project's vite.config.ts. This ensures the Svelte development server runs over HTTPS. ```typescript import { defineConfig } from 'vite' import { svelte } from 'vite-plugin-svelte' import basicSsl from '@vitejs/plugin-basic-ssl' export default defineConfig({ plugins: [ basicSsl(), svelte() ] }) ``` -------------------------------- ### Write Certificate to File Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/api-reference-certificate.md Writes the generated PEM-encoded certificate and private key to a file using Node.js 'fs' module. ```typescript import fs from 'node:fs' fs.writeFileSync('cert.pem', cert2) ``` -------------------------------- ### Express Backend Server with Basic SSL Certificate Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Set up an Express backend server to use the certificate generated by vite-plugin-basic-ssl. This allows the backend to be accessed via HTTPS, enabling proxying from the Vite frontend. ```typescript import express from 'express' import https from 'node:https' import fs from 'node:fs' import path from 'node:path' const app = express() app.get('/api/data', (req, res) => { res.json({ message: 'Hello' }) }) const certPath = path.join( process.cwd(), 'node_modules/.vite/basic-ssl/_cert.pem' ) const cert = fs.readFileSync(certPath, 'utf8') const server = https.createServer({ cert, key: cert }, app) server.listen(3000, () => { console.log('Backend at https://localhost:3000') }) ``` -------------------------------- ### Configure Proxy for Self-Signed Certificates Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md When using a proxy with backend services that use self-signed certificates, set `rejectUnauthorized` to `false` to allow the connection. ```typescript server: { proxy: { '/api': { target: 'https://localhost:3000', changeOrigin: true, rejectUnauthorized: false // For self-signed certs } } } ``` -------------------------------- ### Dynamic Import for Certificate Generation Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/module-structure.md Shows the dynamic import of the certificate generation module within the getCertificate function. This enables code-splitting. ```typescript const content = (await import('./certificate')).createCertificate(...) ``` -------------------------------- ### Node.js Version Compatibility in package.json Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/configuration.md Specifies the required Node.js version range for the plugin. This ensures compatibility with specific Node.js features and APIs. ```json { "engines": { "node": "^18.0.0 || ^20.0.0 || >=22.0.0" } } ``` -------------------------------- ### Custom Cache Directory Configuration Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/configuration.md Specifies a custom directory for storing the generated certificate cache. This is useful for managing certificates in specific locations, such as temporary directories, outside the default Vite cache. ```typescript export default defineConfig({ plugins: [ basicSsl({ name: 'myapp', certDir: '/tmp/dev-certs' }) ] }) ``` -------------------------------- ### Package Export Configuration Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/implementation-overview.md Defines the 'main', 'module', 'types', and 'exports' fields in package.json to configure how the package is imported in different module systems (CommonJS and ESM) and how TypeScript definitions are resolved. ```json { "main": "./dist/index.cjs", "module": "./dist/index.mjs", "types": "./dist/index.d.ts", "exports": { ".": { "import": "./dist/index.mjs", "require": "./dist/index.cjs" } } } ``` -------------------------------- ### Vite Config: Increase Certificate TTL Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Configure the basicSsl plugin to use a longer Time-To-Live (TTL) for the generated certificate. This reduces the frequency of needing to regenerate the certificate. ```typescript basicSsl({ ttlDays: 365 }) ``` -------------------------------- ### Index TS Dependencies Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/module-structure.md Lists the internal and Node.js built-in modules imported by src/index.ts. Note the dynamic import for './certificate'. ```typescript import path from 'node:path' import { promises as fsp } from 'node:fs' import type { Plugin } from 'vite' import { isCertificateExpired } from './certificate-expiration' ``` -------------------------------- ### Node.js HTTPS Server with Basic SSL Certificate Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Create a Node.js HTTPS server using the certificate generated by vite-plugin-basic-ssl. This is useful for backend services that need to be accessed over HTTPS. ```typescript import https from 'node:https' import fs from 'node:fs' const cert = fs.readFileSync('node_modules/.vite/basic-ssl/_cert.pem', 'utf8') https.createServer( { cert, key: cert }, (req, res) => { // Your API handler res.end('Hello') } ).listen(3000) ``` -------------------------------- ### Persist Certificates in Docker Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md Configure a specific directory for certificate storage to ensure they persist across Docker container restarts. Volume-mount this directory for persistent storage. ```typescript basicSsl({ certDir: '/app/.certs' }) ``` -------------------------------- ### Add Domain to Certificate Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/README.md When encountering domain mismatch errors, add the specific domain to the `domains` option in the plugin configuration. Update your system's hosts file to map the domain to localhost. ```typescript basicSsl({ domains: ['myapp.local'] }) ``` -------------------------------- ### Vite Proxy Configuration for HTTP Backend Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/integration-guide.md Configure Vite's server proxy to forward requests to an HTTP backend. This is useful when the backend does not support HTTPS during development. ```typescript export default defineConfig({ plugins: [basicSsl()], server: { proxy: { '/api': { target: 'http://localhost:3000', // HTTP backend changeOrigin: true } } } }) ``` -------------------------------- ### Create Certificate with Custom Options Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/api-reference-certificate.md Generates a self-signed certificate with a custom common name, additional domains, and a specified validity period in days. ```typescript // With custom domain and name const cert2 = createCertificate( 'myapp.local', ['*.myapp.local', 'api.myapp.local'], 60 // valid for 60 days ) ``` -------------------------------- ### Import Named Exports Source: https://github.com/vitejs/vite-plugin-basic-ssl/blob/main/_autodocs/INDEX.md Import specific functions like getCertificate, createCertificate, isCertificateExpired, and parseNonStandardDateString from the plugin. ```typescript import { getCertificate } from '@vitejs/plugin-basic-ssl' import { createCertificate } from '@vitejs/plugin-basic-ssl' import { isCertificateExpired } from '@vitejs/plugin-basic-ssl' import { parseNonStandardDateString } from '@vitejs/plugin-basic-ssl' ```