Creating Custom Routes Using Next and Express

Right now, we have created a lot of button components in our app. But if we click them, nothing happens. I want each of these buttons to take me somewhere else.

To do this, we can set up our own server configuration inside Next. Lets start doing that by creating a new file named server.js inside the root directory of the app.

In this file, we will need to import express and next . We will also need to define a couple of things, such as the port , dev , app , and handle . dev will tell our server that the environment we are currently in is development and not production .

const express = require('express');

const next = require('next');

const port = parseInt(process.env.PORT, 10) || 3000

const dev = process.env.NODE_ENV !== 'production';

const app = next({dev});

const handle = app.getRequestHandler();

We can now start configuring our server. All the server-related code will be wrapped inside the app.prepare() function. This will allow us to use Next’s features, even though we are no longer going to use Next’s built-in server.

We will start by creating a const named server and set it to the value of express() . We can then use server to define different routes within the app. Let’s start by creating a route named /marvel . I am going to define this route as the default route, so that even when a user enters the usual URL of localhost:3000 , the server will automatically append /marvel to the URL.

app.prepare().then(() => {

const server = express();

server.get('/marvel', (req, res) => app.render(req, res, '/'));

})

We can also enforce this URL redirection by telling our server to redirect any user that enters the old URL — the one without any text appended to it.

server.get('/', (req, res) => res.redirect(301, '/marvel'));

Finally, we can setup one last route that will handle all other requests that can be made to our server.

server.get('/*', (req, res) => handle(req, res));

But we are not done yet. After setting up the routes, we still need to tell the app where to listen for the HTTP requests.



if(err) throw err

console.log(`Listening on

}); server.listen(port, err => {if(err) throw errconsole.log(`Listening on http://localhost:${port}`) });

One last thing left to do in this section. Our app is still using Next’s built-in server. We need to tell it use the Node server instead and use the configurations that we have just written.

So go to the package.json file and change the dev script to:

"dev": "node server.js"