4. Deploying Express.js API to Vercel (Serverless)
Vercel can deploy your Express.js application as serverless functions. This requires a vercel.json configuration file at the root of your project.
4.1. Create vercel.json
At the root of your monorepo (e.g., my-fullstack-app/vercel.json), create a vercel.json file to tell Vercel how to handle your API routes.
// vercel.json
{
"rewrites": [
{
"source": "/api/(.*)",
"destination": "/api/"
}
],
"functions": {
"api/index.js": {
"runtime": "node tolerant",
"memory": 1024,
"maxDuration": 10
}
}
}
Explanation:
rewrites: This rule routes all requests to/api/*to yourapi/index.jsserverless function.functions: Defines specific settings for your serverless functions.api/index.jsis specified as the entry point, using thenode tolerantruntime, with 1024MB memory and a 10-second max duration. Adjust these values as needed.
4.2. Ensuring Correct Dependencies
Vercel will install dependencies for both your Next.js app and your api/ directory. Make sure each package.json correctly lists its dependencies.
For example, express and cors should be in api/package.json's dependencies.
4.3. Deploy and Test
Push your changes to your Git repository. Vercel will detect the vercel.json file and deploy your Express.js API as serverless functions alongside your Next.js app.
After deployment, you should be able to access your API at https://your-vercel-domain.vercel.app/api/hello.