DEV Community

ccsunny
ccsunny

Posted on

How to start Next.js with express

Why do we need to start Next.js with express?

When using Next.js with Express, we need to initialize the Next.js application before handling any requests. app.prepare() does several important things:

  1. Compiles the Next.js application
  2. Prepares the pages directory Sets up the development or production environment Initializes the Next.js server features
const express = require('express');
const next = require('next');
const session = require('express-session');
const passport = require('passport');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
    const server = express();

    // Express middleware
    server.use(express.json());
    server.use(session({ /* config */ }));
    server.use(passport.initialize());

    // Custom API routes
    server.use('/api/v1', require('./routes/api'));

    // WebSocket setup
    const httpServer = require('http').createServer(server);
    const io = require('socket.io')(httpServer);

    // Real-time features
    io.on('connection', (socket) => {
        // Handle socket events
    });

    // Let Next.js handle page routing
    server.all('*', (req, res) => {
        return handle(req, res);
    });

    httpServer.listen(3000);
});
Enter fullscreen mode Exit fullscreen mode

Details of next options

Check the details in next/src/server/next.ts

Top comments (0)