DEV Community

ccsunny
ccsunny

Posted on

1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay