0
0
NextJSframework~5 mins

Self-hosting with Node.js in NextJS

Choose your learning style9 modes available
Introduction

Self-hosting means running your Next.js app on your own server using Node.js. It lets you control how your app is served and managed.

You want to run your Next.js app on your own server or VPS.
You need full control over the server environment and deployment.
You want to customize server behavior beyond static hosting.
You want to serve dynamic content with server-side rendering.
You want to handle API routes and backend logic in one place.
Syntax
NextJS
node server.js
You run your Next.js app by starting a Node.js server that loads your app.
Usually, you build your app first with 'next build' before running the server.
Examples
Build your Next.js app and then start the Node.js server to serve it.
NextJS
npm run build
npm start
Run a custom Node.js server file that imports and serves your Next.js app.
NextJS
node server.js
Sample Program

This is a simple custom Node.js server for Next.js. It prepares the app, then creates an HTTP server that handles all requests using Next.js's request handler. It listens on port 3000.

NextJS
import { createServer } from 'http';
import { parse } from 'url';
import next from 'next';

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

app.prepare().then(() => {
  createServer((req, res) => {
    const parsedUrl = parse(req.url || '', true);
    handle(req, res, parsedUrl);
  }).listen(3000, () => {
    console.log('> Ready on http://localhost:3000');
  });
});
OutputSuccess
Important Notes

Always run 'next build' before starting the server in production.

Use environment variables to switch between development and production modes.

Self-hosting lets you add custom server logic if needed.

Summary

Self-hosting with Node.js runs your Next.js app on your own server.

You build the app, then start a Node.js server to serve it.

This approach gives you control and flexibility over your app's backend.