Open In App

Next.js Custom Server

Last Updated : 08 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Next.js is a react-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. If you have little experience in react and looking forward to knowing more about react ecosystem then you should have knowledge about the Next.js framework.

A custom server in Next.js is a Node.js script that runs in the same process as the Next.js development server. This script can handle additional server-side logic, such as handling API routes, handling errors, and setting custom headers.

Here are the step-by-step instructions for creating a custom server in a Next.js application:

Step 1 (Create a new server file): In the root of your Next.js project, create a new file called server.js. This file will contain the code for your custom server.

Step 2 (Import next and http): In the server.js file, import the next and http modules. The next module is the Next.js server, and the http module is the built-in Node.js HTTP module.

Step 3 (Create an instance of the Next.js server): Using the imported next module, create an instance of the Next.js server. This instance will handle the basic server-side rendering of your application.

Step 4 (Handle API routes): In the server.js file, add your own custom routes for handling API requests. You can use any routing library, such as Express.js, to handle these routes.

The server.js file code will look like:

Javascript




const next = require('next')
const http = require('http')
  
const app = next({dev: process.env.NODE_ENV !== 'production'})
  
app.prepare().then(() => {
 const server = http.createServer((req, res) => {
   // Handle API routes
   if (req.url.startsWith('/api')) {
     // Your API handling logic here
   } else {
     // Handle Next.js routes
     return app.getRequestHandler()(req, res)
   }
 })
 server.listen(3000, (err) => {
   if (err) throw err
   console.log('> Ready on http://localhost:3000')
 })
})


Step 5. In the package.json file, add a new script that starts the custom server.

Javascript




"scripts": {
   "dev": "node server.js"
 },


Step 6 (Start the development server): Using the command prompt, navigate to the root of the project and start the development server by running the following command in terminal

npm run dev

In this example, the custom server is handling requests that begin with /api, and any other requests are handled by the Next.js server. This allows you to handle custom server-side logic, such as handling API routes, handling errors, and setting custom headers.

Reference: https://nextjs.org/docs/advanced-features/custom-server



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads