2. Express.js API Integration & Development
To ensure your Next.js frontend can communicate with your Express.js backend, you'll need to handle API routes and potentially CORS.
2.1. Handling CORS in Express.js
During local development, you might encounter Cross-Origin Resource Sharing (CORS) issues. Install the cors package in your api/ directory:
cd api
npm install cors
Then, update api/index.js:
// api/index.js
const express = require('express');
const cors = require('cors'); // Import cors
const app = express();
app.use(cors()); // Use cors middleware
app.use(express.json());
app.get('/api/hello', (req, res) => {
res.status(200).send('Hello from Express.js API!');
});
module.exports = app;
For production, you should configure CORS to allow requests only from your Next.js frontend domain.
2.2. Consuming the API in Next.js
Your Next.js frontend (e.g., nextjs-frontend/pages/index.js) can fetch data from your Express.js API. During local development, Express.js might run on a different port (e.g., 3001), while Next.js runs on 3000.
// nextjs-frontend/pages/index.js
import { useEffect, useState } from 'react';
function HomePage() {
const [message, setMessage] = useState('Loading...');
useEffect(() => {
fetch('/api/hello') // This will be proxied or routed by Vercel in production
.then(res => res.text())
.then(setMessage);
}, []);
return <div>{message}</div>;
}
export default HomePage;
For local development, you might need to set up a proxy in next.config.js or run Express.js on a different port and use http://localhost:3001/api/hello. However, for Vercel deployment, we'll configure Vercel to route /api/* requests directly to your Express.js serverless functions.