How to Deploy a Lovable App to Vercel with Custom and Wildcard Domains Made Simple
How to Deploy a Lovable App to Vercel with Custom and Wildcard Domains Made Secure and Scalable
Modern web applications generated via platforms like Lovable require robust, secure, and production-ready hosting architectures. Transitioning a client-side or hybrid application from a development environment to a production edge network such as Vercel involves precise configuration of routing layers, domain name system (DNS) records, SSL/TLS certificate provisioning, and wildcard subdomain handling. Inadequate configuration during this deployment lifecycle frequently leads to mixed-content warnings, broken SSL handshakes, DNS propagation delays, and multi-tenant routing failures.
This technical guide details the exact production engineering procedures required to export, build, deploy, and secure a Lovable application on Vercel. It covers standard custom domain mapping, advanced wildcard subdomain architectures for multi-tenant applications, edge middleware routing logic, security hardening headers, and comprehensive validation checks.
Problem Statement & Infrastructure Impact
Deploying modern Single Page Applications (SPAs) or static-dynamic hybrid applications introduces architectural challenges related to client-side routing, asset caching, and multi-tenant subdomain resolution. When an application utilizes Lovable to scaffold React, Vue, or Next.js codebases, the resulting output relies heavily on client-side routing structures or edge functions. If deployed without correct routing fallbacks, direct access to deep-linked URLs (e.g., https://yourdomain.com/dashboard/settings) results in HTTP 404 errors served by the edge cache because the web server attempts to locate a physical file path corresponding to the URI path.
Chat with an engineer on WhatsApp within 15 minutes.
Furthermore, implementing dynamic wildcard subdomains (such as *.yourdomain.com) to support tenant-specific workspaces introduces complex DNS validation and TLS certificate generation overhead. Standard certificate authorities require stringent validation methods (such as DNS-01 challenges) for wildcards, and edge routing platforms must accurately intercept the Host header to parse the subdomain prefix before passing execution context down to the application layer. Misconfigurations in these layers expose the application to host header injection vulnerabilities, cache poisoning, and certificate mismatch errors.
Root Cause Analysis & Edge Architecture
Vercel operates on an edge network that caches static assets globally while routing dynamic execution to Serverless Functions or Edge Functions. Understanding the request lifecycle is critical for successful deployment:
- DNS Resolution: When a user navigates to a custom domain or wildcard subdomain, the request resolves to Vercel’s Anycast IP network via A, AAAA, or CNAME records.
- Edge Termination: TLS termination occurs at the edge node nearest the user. Vercel automatically provisions and renews Let’s Encrypt SSL certificates. For wildcard domains, a Subject Alternative Name (SAN) certificate must cover both the apex domain and all immediate subdomains.
- Routing and Rewrite Execution: The Vercel routing engine evaluates the incoming request against
vercel.jsonconfiguration rules. For SPAs, all routes must be rewritten to/index.htmlto allow client-side routers (such as React Router) to handle path rendering. - Middleware Processing: For wildcard multi-tenancy, Edge Middleware intercepts the request, extracts the tenant slug from the
Hostheader, validates the tenant against a database or configuration store, and injects custom headers or rewrites the request internally to a dynamic handler page (e.g.,/tenant/[slug]/page).
Step-by-Step Implementation & Deployment Guide
The following procedures outline the end-to-end process of exporting your Lovable codebase, configuring build parameters, deploying to Vercel, and mapping custom and wildcard domains.
Step 1: Codebase Export and Git Repository Initialization
Before initiating deployments on Vercel, the application source code must be version-controlled and structured with appropriate build scripts.
- Export your project archive from Lovable or push the repository directly to your GitHub, GitLab, or Bitbucket account.
- Ensure your root directory contains a standard Node.js package manager configuration file (
package.json) defining precise build scripts and dependency versions.
{
"name": "lovable-production-app",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.0"
},
"devDependencies": {
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.3",
"@vitejs/plugin-react": "^4.3.1",
"typescript": "^5.5.3",
"vite": "^5.3.4"
}
}
Step 2: Configuring Vercel Build and Output Rules
To prevent routing failures and build errors, explicitly define your project structure using a vercel.json file placed in the root directory of your repository. This configuration forces Vercel to handle Single Page Application routing correctly.
{
"version": 2,
"builds": [
{
"src": "package.json",
"use": "@vercel/static-build",
"config": { "distDir": "dist" }
}
],
"routes": [
{ "handle": "filesystem" },
{ "src": "/(.*)", "dest": "/index.html" }
],
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "X-Content-Type-Options", "value": "nosniff" },
{ "key": "X-Frame-Options", "value": "DENY" },
{ "key": "X-XSS-Protection", "value": "1; mode=block" },
{ "key": "Strict-Transport-Security", "value": "max-age=63072000; includeSubDomains; preload" }
]
}
]
}
Step 3: Deploying the Application via Vercel CLI or Dashboard
You can deploy your repository either through the Vercel web dashboard by importing your Git repository, or via the Vercel Command Line Interface (CLI) for automated CI/CD pipelines.
To deploy using the Vercel CLI, execute the following terminal commands:
# Install the Vercel CLI globally
npm install -g vercel
# Authenticate with your Vercel account
vercel login
# Initialize and deploy to a production environment
vercel --prod
During the CLI deployment prompt, confirm the following settings:
- Set up and deploy? Yes
- Which scope do you want to deploy to? Select your personal account or team.
- Link to existing project? No (for initial setup).
- What’s your project name? lovable-app-production.
- In which directory is your code located? ./ (Root).
- Auto-detected project settings (Vite): Confirm build command (
npm run build) and output directory (dist).
Step 4: Mapping Custom Apex and Subdomains
Once your deployment is live at a *.vercel.app preview URL, map your production custom domain.
- Navigate to your project dashboard on Vercel, click Settings, and select Domains.
- Enter your primary production domain (e.g.,
example.com) and click Add. Vercel will suggest adding the apex domain along with thewwwredirect. - Configure the required DNS records within your DNS provider (Cloudflare, AWS Route 53, etc.):
| Type | Name / Host | Value / Target | TTL |
|---|---|---|---|
| A | @ | 76.76.21.21 | Auto / 300s |
| CNAME | www | cname.vercel-dns.com | Auto / 300s |
Step 5: Implementing Wildcard Domains and Edge Middleware
To support dynamic multi-tenant architectures where users access unique instances via *.example.com, configure a wildcard domain mapping.
- In the Vercel Domains settings panel, add the wildcard entry:
*.example.com. - Vercel will prompt you to add a wildcard DNS CNAME record:
| Type | Name / Host | Value / Target | TTL |
|---|---|---|---|
| CNAME | * | cname.vercel-dns.com | Auto / 300s |
To capture incoming wildcard requests and route them dynamically based on the subdomain, create a Vercel Edge Middleware script named middleware.ts in the root or src directory of your project.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const url = request.nextUrl;
const hostname = request.headers.get('host') || '';
// Define your production root domain
const rootDomain = 'example.com';
// Check if the request is coming from a subdomain
if (hostname.endsWith(`.${rootDomain}`) && hostname !== `www.${rootDomain}`) {
const subdomain = hostname.replace(`.${rootDomain}`, '');
// Prevent handling system subdomains
if (subdomain !== 'app' && subdomain !== 'api') {
// Rewrite the request internally to a dynamic tenant handler path
url.pathname = `/tenant/${subdomain}${url.pathname}`;
return NextResponse.rewrite(url);
}
}
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
};
Production Hardening, Caching, and Edge Cases
Deploying production applications to edge networks introduces caching and security considerations that require explicit mitigation strategies.
Cache-Control and Asset Invalidation
Vercel automatically caches static assets with immutable cache headers (Cache-Control: public, max-age=31536000, immutable). However, dynamic entry points and HTML files require careful cache tuning to prevent users from serving stale application bundles after a new deployment.
Ensure your vercel.json or server response headers explicitly control HTML caching:
{
"headers": [
{
"source": "/index.html",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=0, must-revalidate"
}
]
}
]
}
SSL/TLS Certificate Limitations for Wildcards
When deploying wildcard domains (*.example.com), be aware that single-level wildcards do not cover nested subdomains (e.g., sub.tenant.example.com will fail SSL validation). If nested subdomains are required, architecture must be adjusted to single-level tenant slugs.
Mitigating Host Header Injection
When processing multi-tenant requests via wildcard domains, relying blindly on the incoming Host header without strict regex validation exposes the application to Host Header Injection attacks. Always sanitize the extracted subdomain string to alphanumeric characters and hyphens only before querying downstream databases.
const isValidSubdomain = (sub: string): boolean => {
const regex = /^[a-zA-Z0-9-]+$/;
return regex.test(sub) && sub.length > 0 && sub.length <= 63;
};
Diagnostic Verification & Validation Matrix
Execute the following verification checklist and command-line diagnostics to confirm that your custom domain, wildcard routing, SSL configuration, and security headers are operating correctly in production.
- DNS Propagation Check: Verify global DNS resolution using
digornslookup. - SSL Handshake Verification: Inspect certificate validity and SAN coverage using
openssl. - Header Security Audit: Confirm presence of HSTS, CSP, and anti-clickjacking headers via
curl.
# Verify DNS A and CNAME records propagation
dig A example.com +short
dig CNAME *.example.com +short
# Verify SSL certificate chain and Subject Alternative Names
openssl s_client -connect example.com:443 -servername example.com -showcerts
# Inspect HTTP response headers and security policies
curl -I https://example.com
curl -I https://tenant1.example.com
| Verification Test | Expected Result | Diagnostic Command |
|---|---|---|
| Apex Domain Resolution | Resolves to Vercel IP (76.76.21.21) | dig +short example.com A |
| Wildcard Subdomain Resolution | Resolves to cname.vercel-dns.com |
dig +short randomtest.example.com CNAME |
| SSL Certificate Expiry & SAN | Valid certificate including *.example.com |
openssl s_client ... |
| HSTS Header Present | Strict-Transport-Security: max-age=63072000... |
curl -I https://example.com |
| SPA Fallback Routing | HTTP 200 on deep-link routes (no 404) | curl -I https://example.com/dashboard/settings |
Proper execution of these steps ensures that your Lovable application deployed to Vercel maintains high availability, robust cryptographic security at the edge, and reliable multi-tenant wildcard routing.
Is Your Website Fast & Secure?
Run an instant scan for security vulnerabilities, bloated plugins, and TTFB latency.
Need Help Securing or Speeding Up Your Site?
Get 24/7 proactive security WAF, daily cloud backups, and sub-second speed optimization from ₹3,470/mo.