Vercel 06 ▲ Project Configuration (vercel.json) — Defining rewrites, redirects, custom headers, clean URLs, and function settings
The vercel.json file acts as the primary configuration manifest for Vercel deployments. While Vercel handles most framework-specific configurations automatically through zero-config deployment, this file is the override mechanism used to define project-level behavior that standard frameworks or build systems might not cover or where specific platform-level control is required. It allows developers to dictate how the Vercel Edge Network handles incoming requests, manages security, and executes serverless functions.
This chapter details the schema of vercel.json and how to implement complex routing logic. We will explore how to manipulate URL structures through rewrites and redirects, how to inject security and caching headers, and how to fine-tune the serverless execution environment for optimal performance and cost management.
Key point: The vercel.json file is a declarative JSON configuration that overrides automatic framework detection, providing granular control over the Vercel Edge Network’s request handling, security policy injection, and serverless runtime parameters.
Why X exists
The URL normalization problem.
Modern web applications often have evolving URL structures. When migrating legacy applications or refactoring existing routing paths, preserving SEO equity and ensuring users land on the correct content is paramount. vercel.json provides a centralized routing layer to manage this without modifying the underlying application source code.
The serverless performance problem.
Serverless functions on Vercel run within specific regional constraints and resource limits. Default settings work for most use cases, but high-traffic endpoints often require specific timeout limits, memory allocations, or region pinning to minimize latency and manage cloud infrastructure costs.
The security header problem.
Ensuring consistent security policies like Content Security Policy (CSP), HSTS, or CORS across every single route in an application is difficult to maintain manually within framework code. Centralizing these definitions in the infrastructure layer ensures they are applied universally, even for static assets.
The path handling problem.
Different frameworks handle trailing slashes, .html extensions, and canonical URLs differently. vercel.json allows developers to enforce a consistent URL pattern across the entire project, ensuring clean, predictable URLs regardless of the underlying build tool’s defaults.
The build pipeline integration problem.
Some projects require static build artifacts that need custom routing rules which don’t map cleanly to framework-specific routing libraries. By abstracting routing into vercel.json, developers separate infrastructure concerns from application logic, making the deployment configuration portable and platform-agnostic.
a. Rewrites, Redirects, and Clean URLs
Routing in vercel.json is handled by the rewrites and redirects arrays. A redirect forces the browser to change the URL, resulting in a 301 (Permanent) or 308 (Permanent) status code. A rewrite masks the path; the browser URL remains the same, but the Edge Network fetches the resource from a different internal path.
{
"redirects": [
{ "source": "/old-blog", "destination": "/blog", "permanent": true }
],
"rewrites": [
{ "source": "/api/users/:path", "destination": "/api/internal/:path" }
]
}
Rewrites are powerful for bridging legacy systems. You can route an incoming request for /api/users/123 to an internal path like /api/internal/123 without the user or the client-side code ever knowing the underlying file structure has changed. This is commonly used for proxying requests to different services or micro-frontends.
cleanUrls is a specific boolean flag that tells Vercel to automatically strip the .html extension from files in the output directory. When true, a file at /contact.html is accessible at /contact.
{
"cleanUrls": true,
"trailingSlash": false
}
The trailingSlash property enforces a consistent URL shape. Setting it to false removes trailing slashes (e.g., /about/ becomes /about), while true enforces them (e.g., /about becomes /about/). This prevents duplicate content issues for SEO.
b. Custom Headers
Security and caching are critical for edge-deployed applications. The headers property allows you to inject custom HTTP headers into responses based on the request path. This is the primary way to implement security protocols like Strict-Transport-Security or to optimize browser caching.
{
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "X-Content-Type-Options", "value": "nosniff" },
{ "key": "Cache-Control", "value": "public, max-age=3600, must-revalidate" }
]
}
]
}
The source field uses glob patterns to match paths. The (.*) pattern matches all routes. The headers array defines key-value pairs that the Edge Network will attach to every response matching that source. This is superior to framework-level header injection because it applies even to static files (like images, CSS, or JS bundles) that framework logic never touches.
c. Function Settings
Vercel functions are serverless by default, but they often need tuning to fit production requirements. The functions object allows you to override settings for specific API routes, including the runtime version, memory allocation, and the maximum execution duration (timeout).
{
"functions": {
"api/heavy-task.js": {
"memory": 1024,
"maxDuration": 30
}
}
}
This configuration enables scaling. A standard function might only need 128MB of memory, but a data-processing task might require 1GB. By mapping the file path (or glob pattern) to the configuration object, you ensure that only the heavy functions consume higher resources, keeping the overall cloud bill efficient.
Complete Example Session
// ============================================
// PART 1: ROOT CONFIGURATION
// ============================================
{
"cleanUrls": true,
"trailingSlash": false,
// ============================================
// PART 2: REDIRECTS
// ============================================
"redirects": [
{ "source": "/v1/:path*", "destination": "/v2/:path*", "permanent": true }
],
// ============================================
// PART 3: REWRITES
// ============================================
"rewrites": [
{ "source": "/dashboard", "destination": "/app/index.html" }
],
// ============================================
// PART 4: HEADERS
// ============================================
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "Strict-Transport-Security", "value": "max-age=63072000; includeSubDomains" }
]
}
],
// ============================================
// PART 5: FUNCTION TUNING
// ============================================
"functions": {
"api/upload.js": {
"memory": 1024,
"maxDuration": 60
}
}
}
This session demonstrates a full project configuration: enabling clean URLs, handling major API version transitions via redirects, proxying dashboard requests via rewrites, enforcing HSTS security, and increasing resources for file upload functions.
Quick Reference
Routing Controls
| Property | Description |
|---|---|
rewrites | Masks URLs, fetches internally |
redirects | Changes browser URL (301/308) |
cleanUrls | Removes .html from paths |
trailingSlash | Enforces / or no / |
Header Injection
| Property | Description |
|---|---|
source | Glob pattern for target files |
headers | Array of key-value objects |
key | HTTP Header name |
value | Header value string |
Serverless Tuning
| Property | Description |
|---|---|
memory | MB allocated to function |
maxDuration | Seconds until timeout |
regions | Geographic deployment zone |
Best Practices
✅ Do This:
// Enforce HTTPS security headers
{ "key": "Strict-Transport-Security", "value": "max-age=63072000" } // ✅
// Use perm redirects for SEO
{ "source": "/old", "destination": "/new", "permanent": true } // ✅
// Scale memory only where needed
"api/process.js": { "memory": 1024 } // ✅
// Use rewrites to mask infrastructure
{ "source": "/api/(.*)", "destination": "/proxy/$1" } // ✅
❌ Don’t Do This:
// Never hardcode redirects for every single route
"redirects": [{ "source": "/a", ... }, { "source": "/b", ... }] // ❌
// Don't set memory limits too high globally
"functions": { "*": { "memory": 3008 } } // ❌
// Avoid redirects when a rewrite will suffice
{ "source": "/api", "destination": "/new-api", "permanent": true } // ❌
// Don't inject cache-control on dynamic auth paths
"headers": [{ "source": "/login", "headers": [ "Cache-Control" ] }] // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Rewrite Loop | Circular dependency | Check source/dest paths |
| Header Conflict | Framework also sends headers | Remove framework header logic |
| Timeout Error | maxDuration too low | Increase function duration |
| SEO Penalty | Redirect loop | Verify 301 vs 302 logic |
Real-World Examples
1. Simple 301 Redirect
{ "source": "/blog/post-1", "destination": "/posts/1", "permanent": true }
2. Rewrite to API
{ "source": "/api/v1/:path*", "destination": "/api/v2/:path*" }
3. Custom Cache Header
{ "key": "Cache-Control", "value": "s-maxage=86400" }
4. Clean URLs
{ "cleanUrls": true }
5. Memory Limit
"api/generate-pdf.js": { "memory": 2048 }
6. CORS Header
{ "key": "Access-Control-Allow-Origin", "value": "*" }
7. Trailing Slash
{ "trailingSlash": true }
8. Function Timeout
"api/long-task.js": { "maxDuration": 60 }
9. HSTS Security
{ "key": "Strict-Transport-Security", "value": "max-age=31536000" }
10. Wildcard Rewrite
{ "source": "/shop/:slug", "destination": "/product?id=:slug" }
Visual
The Request Flow
┌──────────────────────────────────────────────────────┐
│ USER REQUEST (browser) │
│ │ │
│ ▼ │
│ VERCEL EDGE NETWORK │
│ ┌──────────────────────┐ │
│ │ vercel.json Rules │ (Rewrites/Headers) │
│ └──────────┬───────────┘ │
│ │ │
│ ▼ │
│ BACKEND / SERVERLESS FUNCTION / STATIC ASSET │
└──────────────────────────────────────────────────────┘
Redirect vs Rewrite
┌───────────────────────────┐ ┌───────────────────────────┐
│ REDIRECT (301) │ │ REWRITE │
│ │ │ │
│ 1. User asks /old │ 1. User asks /proxy │
│ 2. Server says 301 /new │ 2. Edge fetches /internal │
│ 3. User goes to /new │ 3. User sees content │
│ 4. URL changes │ 4. URL stays /proxy │
└───────────────────────────┘ └───────────────────────────┘
Header Injection
┌──────────────────────────────────────────────────────────┐
│ RESPONSE FROM ORIGIN │
│ [200 OK] │
│ │
│ [INJECTION LAYER] ◄─── vercel.json headers added here │
│ │
│ [FINAL RESPONSE TO USER] │
│ [200 OK] + [Strict-Transport-Security] │
└──────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Config file | vercel.json |
| Routing | rewrites, redirects |
| Security | headers |
| Function config | functions |
| URL shape | cleanUrls, trailingSlash |
| Matches | Glob patterns |
| Scope | Project-wide |
| Status Code | 301, 308 for redirects |
Key takeaways:
vercel.jsonacts as an infrastructure abstraction. It allows you to define routing and security policies that exist outside your application code, ensuring they apply to static assets and serverless functions alike.- Rewrites maintain URL consistency. They are ideal for proxying requests or migration strategies where you need to change the destination path without the user knowing.
- Redirects are for resource movement. Use them to signal to browsers and search engines that a URL has permanently moved via 301/308 status codes.
- Security headers are mandatory. Use the
headersproperty to apply standard security headers like HSTS and CSP across your entire domain automatically. - Scale resources granularly. Use the
functionsproperty to tailor memory and execution time to specific API routes rather than applying a blanket policy to the whole project.
Remember: vercel.json is the lever for edge-network behavior. Treat it as a critical infrastructure file that dictates how traffic flows and how serverless resources behave. Always validate your regex and glob patterns to avoid accidental routing loops or misconfigured headers that could affect the entire deployment.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!