No articles found
Try different keywords or browse our categories
Fix: 502 Bad Gateway on Vercel
Complete guide to fix '502 Bad Gateway' error on Vercel. Learn how to resolve server gateway issues and improve Vercel deployment stability.
The ‘502 Bad Gateway’ error on Vercel occurs when the Vercel edge network receives an invalid response from your serverless functions or when your application takes too long to respond to requests.
How the Error Happens
This error typically occurs when:
- Serverless functions exceed timeout limits
- Application crashes or throws unhandled errors
- Cold start issues with serverless functions
- Memory limits exceeded in serverless functions
- Network connectivity issues between Vercel and your functions
Solution 1: Optimize Serverless Function Timeouts
// ❌ Long-running operations causing timeouts
// api/slow-endpoint.js
export default async function handler(req, res) {
// ❌ This might exceed timeout (max 10s for Hobby, 60s for Pro)
await performSlowOperation(); // ❌ Could take too long
res.status(200).json({ success: true });
}
// ✅ Optimize function execution time
// api/fast-endpoint.js
export default async function handler(req, res) {
try {
// ✅ Keep operations fast and efficient
const result = await performQuickOperation();
res.status(200).json({ success: true, data: result });
} catch (error) {
// ✅ Handle errors gracefully
res.status(500).json({ error: 'Internal server error' });
}
}
Solution 2: Implement Proper Error Handling
// ✅ Robust error handling for Vercel functions
// api/robust-endpoint.js
export default async function handler(req, res) {
try {
// ✅ Wrap everything in try-catch
const data = await fetchData();
if (!data) {
return res.status(404).json({ error: 'Data not found' });
}
res.status(200).json({ data });
} catch (error) {
console.error('API Error:', error);
res.status(500).json({
error: 'Internal server error',
message: process.env.NODE_ENV === 'development' ? error.message : undefined
});
}
}
Solution 3: Optimize Memory Usage
// ✅ Optimize memory usage in serverless functions
// api/memory-optimized.js
export default async function handler(req, res) {
try {
// ✅ Process data in chunks to avoid memory issues
const largeDataSet = await fetchLargeDataSet();
// ✅ Use streaming or pagination for large data
const processedData = largeDataSet.slice(0, 100); // ✅ Limit response size
res.status(200).json({
data: processedData,
total: largeDataSet.length
});
} catch (error) {
res.status(500).json({ error: error.message });
}
}
Solution 4: Configure Vercel Settings
// ✅ In vercel.json, configure function settings
{
"functions": {
"api/**/*.js": {
"maxDuration": 60, // ✅ Increase timeout (Pro plan)
"memory": 1024, // ✅ Increase memory allocation
"runtime": "nodejs18.x" // ✅ Specify runtime
}
},
"headers": [
{
"source": "/api/(.*)",
"headers": [
{
"key": "Access-Control-Allow-Origin",
"value": "*"
}
]
}
]
}
Solution 5: Implement Health Checks and Monitoring
// ✅ Health check endpoint
// api/health.js
export default async function handler(req, res) {
try {
// ✅ Quick health check
const startTime = Date.now();
// ✅ Check database connectivity if applicable
// await db.connect();
const responseTime = Date.now() - startTime;
res.status(200).json({
status: 'healthy',
responseTime: `${responseTime}ms`,
timestamp: new Date().toISOString()
});
} catch (error) {
res.status(503).json({
status: 'unhealthy',
error: error.message,
timestamp: new Date().toISOString()
});
}
}
Solution 6: Handle Cold Starts
// ✅ Optimize for cold starts
// api/optimized.js
let dbConnection; // ✅ Initialize outside handler
async function initDB() {
if (!dbConnection) {
// ✅ Lazy initialization
dbConnection = await connectToDatabase();
}
return dbConnection;
}
export default async function handler(req, res) {
try {
const db = await initDB();
const data = await db.getData(req.query);
res.status(200).json({ data });
} catch (error) {
res.status(500).json({ error: error.message });
}
}
Solution 7: Use Edge Functions for Faster Response
// ✅ Use Edge Functions for faster response times
// api/edge-endpoint.js
export const config = {
runtime: 'edge', // ✅ Use Edge Runtime
};
export default async function handler(request) {
try {
// ✅ Edge functions have faster cold starts
const url = new URL(request.url);
const param = url.searchParams.get('param');
return new Response(
JSON.stringify({ message: `Hello from edge! Param: ${param}` }),
{
status: 200,
headers: {
'Content-Type': 'application/json',
},
}
);
} catch (error) {
return new Response(
JSON.stringify({ error: 'Internal server error' }),
{
status: 500,
headers: {
'Content-Type': 'application/json',
},
}
);
}
}
Solution 8: Monitor and Debug Vercel Deployments
// ✅ Add logging for debugging
// utils/logger.js
export function log(level, message, meta = {}) {
const logEntry = {
timestamp: new Date().toISOString(),
level,
message,
meta,
environment: process.env.VERCEL_ENV,
deploymentId: process.env.VERCEL_DEPLOYMENT_ID,
};
console.log(JSON.stringify(logEntry));
}
// ✅ Use in API routes
// api/monitored-endpoint.js
import { log } from '../../utils/logger';
export default async function handler(req, res) {
log('info', 'API endpoint called', { path: req.url, method: req.method });
try {
const startTime = Date.now();
const data = await processRequest(req);
const duration = Date.now() - startTime;
log('info', 'API endpoint completed', { duration, success: true });
res.status(200).json({ data });
} catch (error) {
log('error', 'API endpoint failed', { error: error.message });
res.status(500).json({ error: 'Internal server error' });
}
}
Prevention Tips
- Keep functions fast: Aim for sub-second response times
- Handle errors gracefully: Always wrap in try-catch blocks
- Monitor resource usage: Watch memory and timeout limits
- Use appropriate runtime: Choose the right Node.js version
- Implement caching: Use Vercel’s edge caching when possible
- Test locally: Use Vercel CLI to test before deployment
- Monitor logs: Check Vercel dashboard for error patterns
When to Contact Support
Contact Vercel support when:
- Following all best practices still results in 502 errors
- Suspected infrastructure issues on Vercel’s side
- Need to increase limits beyond standard offerings
- Experiencing regional deployment issues
- Encountering billing-related limitations
Related Articles
Fix: 502 Bad Gateway on PHP sites error and fix
Quick fix for 502 Bad Gateway error on PHP sites. Learn how to resolve server gateway issues and improve PHP application stability.
Fix: 500 Internal Server Error after deploy
Complete guide to fix '500 Internal Server Error after deploy'. Learn how to troubleshoot and resolve server errors after deployment.
Fix: Build exited with code 1 error
Complete guide to fix 'Build exited with code 1' error. Learn how to troubleshoot and resolve build failures in various development environments.