Design Converter
Education
Last updated on Dec 2, 2024
Last updated on Dec 2, 2024
Senior Software Engineer
A Next.js custom server can be a game-changer when you need more control over routing, API routes, and other advanced functionalities. While the default server offered by Next.js is sufficient for most projects, a custom server allows you to extend and tailor the framework to your exact needs.
In this blog, you’ll learn how to set up a custom server, handle req res cycles, and configure server.js file for optimized performance. Whether you're deploying in production or working locally, this tutorial covers everything you need.
By default, Next.js comes with a pre-configured default server that supports pages, static site generation, and API routes. However, there are scenarios where you need to handle custom routes, modify requests, or configure a custom middleware setup. A custom server provides the flexibility to:
Implement custom routes: Simplify URL structures or manage dynamic routes.
Handle specific requests: Add middleware or pre-process req res objects.
Integrate with external libraries like Express for advanced functionalities.
Provide a centralized way to log, parse, or manipulate incoming traffic.
Here’s a step-by-step guide to build your custom server with Next.js:
The heart of your custom server setup is the server.js file. Begin by creating this file in the root directory of your Next.js project.
1touch server.js
Open the server.js file and define your Next.js server. Here’s an example of using Node's HTTP module to start the server:
1const { createServer } = require('http'); 2const next = require('next'); 3 4const app = next({ dev: process.env.NODE_ENV !== 'production' }); 5const handle = app.getRequestHandler(); 6 7app.prepare().then(() => { 8 createServer((req, res) => { 9 // Handle custom routes 10 if (req.url === '/custom-route') { 11 res.end('This is a custom route!'); 12 return; 13 } 14 // Default Next.js routing 15 handle(req, res); 16 }).listen(3000, (err) => { 17 if (err) throw err; 18 console.log('> Ready on http://localhost:3000'); 19 }); 20});
• const app: Initializes the Next.js app.
• req res: Handles incoming HTTP requests and sends responses.
• Custom routes: Redirects or custom handling of specific URLs.
If you need middleware or enhanced routing, integrate Express into your server setup. Update your server.js file:
1const express = require('express'); 2const next = require('next'); 3 4const app = next({ dev: process.env.NODE_ENV !== 'production' }); 5const handle = app.getRequestHandler(); 6 7app.prepare().then(() => { 8 const server = express(); 9 10 // Example: Custom route with Express 11 server.get('/custom-route', (req, res) => { 12 res.send('Handled by Express!'); 13 }); 14 15 // Serve Next.js pages and API routes 16 server.all('*', (req, res) => handle(req, res)); 17 18 server.listen(3000, () => { 19 console.log('> Ready on http://localhost:3000'); 20 }); 21});
Here, Express provides advanced tools for handling requests, logging, and integrating external libraries.
For TypeScript enthusiasts, using ts-node with a Next.js custom server ensures type safety. Install dependencies:
1npm install ts-node typescript @types/node
Rename server.js to server.ts and update your scripts in package.json:
1"scripts": { 2 "dev": "ts-node server.ts" 3}
Modify the server file:
1import { createServer } from 'http'; 2import next from 'next'; 3 4const app = next({ dev: process.env.NODE_ENV !== 'production' }); 5const handle = app.getRequestHandler(); 6 7app.prepare().then(() => { 8 createServer((req, res) => { 9 handle(req, res); 10 }).listen(3000, () => { 11 console.log('> Ready on http://localhost:3000'); 12 }); 13});
A powerful custom server should include error handling and custom routes. Here's how:
In your server.js file:
1server.get('/user/:id', (req, res) => { 2 const { id } = req.params; 3 res.send(`User ID: ${id}`); 4});
1server.use((err, req, res, next) => { 2 console.error(err.stack); 3 res.status(500).send('Something went wrong!'); 4});
When deploying your Next.js custom server, run next build to compile your pages and assets:
1npm run build 2node server.js
This ensures your app is optimized for production with all static files and API routes compiled.
Log Requests: Use middleware to log all incoming requests.
Secure: Implement proper authentication for sensitive routes.
Parse: Validate or parse incoming data (e.g., JSON payloads).
Minimize Dependencies: Use lightweight libraries when possible to reduce bundle size.
Building a Next.js custom server opens up endless possibilities for your application. From managing custom routes to handling advanced requests, a custom setup ensures you have more control over your application. Whether you're using Express, Node, or ts-node, the flexibility to implement tailored features makes this approach ideal for complex projects.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.