How To Add ExpressJS Server To NextJS Application
How To Add ExpressJS Server To NextJS Application
Search Medium
You have 2 free member-only stories left this month. Sign up for Medium and get an extra one.
Member-only story
Landy · Follow
5 min read · Dec 11, 2020
Listen Share
Requirements
ExpressJS
Configuration
Create a tsconfig.server.json file in the application's root directory. We’ll be pointing
the nodemon configuration to this file. Extend the tsconfig.server.json file to use
your original tsconfig.json and include the path to your server directory, as shown
in the code sample below. You’ll also need to add some compiler options to ensure
your project compiles to the right directory, using the correct module.
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 1/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
// tsconfig.server.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "dist",
"noEmit": false,
"sourceMap": true
},
"include": ["src/server"]
}
If you’re using aliases, make sure to update your original tsconfig to include a server
alias if needed.
Next, create a nodemon.json file in the application's root directory. This configuration
will specify which files to watch, ignore, and a path to the server.
// nodemon.json
{
"verbose": true,
"ignore": ["node_modules", ".next"],
"watch": ["server/**/*"],
"ext": "ts json",
"exec": "ts-node --project tsconfig.server.json -r tsconfig-
paths/register -r dotenv/config --files src/server/index.ts"
}
Next, we need to configure the package.json so it starts the server. Change the dev
"scripts": {
"dev": nodemon
. . .
}
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 2/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
Lastly, create a .env file in the projects route directory (if you don’t already have one).
We’ll use this file to store configuration for your server. Within the file specify these
variables to start.
NODE_ENV=dev
SERVER_DOMAIN=localhost
API_PATH=/api/
SERVER_PORT=3000
In the /server create an index.ts file. I’ll run through each part of the file with you, so
don’t worry!
In the index.ts file, import the express , dotenv , and next packages, as well as
contents of ./routes (We’ll add the contents a bit later)
Next, we fetch the data from our .env file. Thanks to dotenv we can easily import
and configure the environment variables.
dotenv.config()
const dev = process.env.NODE_ENV !== 'production
const domain = process.env.SERVER_DOMAIN
const apiPath = process.env.API_PATH
const port = (process.env.SERVER_PORT) as number
Next, create an instance of the next library and pass in the dev variable we defined
earlier. next expects an object with a field called dev , this field determines which
environment to launch the server.
We also get a request handler via getRequestHandler. We will use this to parse HTTP
requests to our server.
Using the next instance, call the prepare method, which returns a promise, and pipe
through the then hook.
next.prepare().then(() => {
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(apiPath, routes)
Within the then callback, instantiate an express instance. We’ll use this instance to
configure our routes and start the server.
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 4/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
These are express middleware functions, and they’re entirely optional for the time
being. express.json() parses middleware requests with JSON payloads and
express.urlencoded parses requests with URL-encoded payloads.
https://expressjs.com/en/api.html#express.json
https://expressjs.com/en/api.html#express.urlencoded
app.use(apiPath, routes)
Uses the variable we defined earlier apiPath to map all the routes we’ll create in
./routes . Therefore, all the routes you create will have the prefix /api/<route_name> .
The full URI will look like this: localhost:3000/api/<route_name> .
The app.all matches requests made under all HTTP verbs (POST, GET, PUT,
DELETE). We use this to ensure all requests made under all routes * are passed
through the request handler we defined earlier.
Then, we listen to the port we defined and log that the server has started.
Your entire file should look like the code shown below:
// ./server/index.ts
import next from 'next'
import express, { Request, Response } from 'express'
import dotenv from 'dotenv'
import routes from './routes/'
next.prepare().then(() => {
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true })) // Uses URL
encoded query strings
Creating Routes
In /server/routes create index.ts and hello-world.routes.ts files.
// ./server/routes/hello-world.routes.ts
import express, { Request, Response } from 'express'
const router = express.Router()
router.get('/', (req: Request, res: Response, next) => {
return res.json({ result: 'Hello World!' })
})
export default router
The next bit of code tells us that GET requests to the root of this route will use
handler specified.
res.json tells us that the response will return a JSON object. You can also use
res.send and send any type of response back (integer, boolean, array, etc.).
Next, in /routes/index.ts file, include the file we created in the previous step, and
use a router to specify this sub-routes name.
// ./server/routes/index.ts
import express from 'express'
import helloWorld from './hello-world.routes.ts'
const router = express.Router()
router.use(`/hello-world`, helloWorld)
export default router
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 7/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
Spin up your application by running npm run dev . Thanks to the power of NextJS,
your server and client will start simultaneously. And thanks to Nodemon, changes to
server files will restart the server.
Hopefully, this quick tutorial was helpful to you! Let me know in the comments of
any issues, tips, or tricks you encountered setting up your server.
Happy coding! ❤
Web Development
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 8/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
Follow
Written by Landy
202 Followers
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 9/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
A rundown of analytical concepts to get started with optimizing search functionality using this
mighty engine.
192 2
438 2
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 10/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
263
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 11/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
Landy
35 1
Explore nodejs developer roadmap for 2023. A step-by-step guide to how to become nodejs
developer, increase knowledge as nodejs developer
587 12
React Dojo
44 2
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 13/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
270 6
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 14/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
950 21
Asim Zaidi
586 1
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 15/16
5/10/23, 9:46 AM How to Add ExpressJS Server to NextJS Application | by Landy | Medium
56
https://simplyy.medium.com/how-to-add-expressjs-server-to-nextjs-application-7061e8538609 16/16