Creating application on server-side – Meet Next.js and Express

Share

The SSR (Server Side Rendering) allows to use to generate dynamic HTML pages – content of these pages is not-known while application is building. The main characteristic of this application is that it can be run on the client side (browser) as well as on the server side.

Why SSR?

SSR applications became popular for many reasons. The most important reason is Google search, for sure. If your JS application is CSR (Client Side Rendered) application, you will have a harder way to get to the top of Google search. Among that, SSR renders application faster and because of that, users with slower internet connection or older mobile devices will have a lot better experience by using you application.

What’s Next.js and what’s Express?

In shortly, Express is the most popular framework for Nodejs, right now. Same as Nodejs, this framework is used on the server side and many people accepted it because of his speed and minimalist code. With the help of Express, you can create also big API systems (Application Programming Interface).

Next.js is React framework with many functionalities, but the main functionality is exactly creating of SSR applications. Among that, with help of this framework, you can easy create static web sites, mobile web applications, SEO-friendly sites, etc. It has automatic splitting of code that allows very fast page loading.

Using of Next.js framework

To start creating SSR application, first step is always installing of necessary libraries and frameworks. Because of that, every project with Next.js framework we should start by installing react, react-dom and next modules (these three modules are next). For that purpose we’re using yarn.

Firstly, in the empty folder, we’re starting initialization of completely new node project and just after that, we’re adding react, react-dom and next.

yarn init
yarn add react react-dom next

After the first command, the console will ask to enter certain informations, like e.g. name of the application, version, author, etc. All these questions can be skipped by just pressing ENTER key for each question (every question already has his own answer and if some questions don’t have – answer is not mandatory).

Milos Ristic Blog2 Slika1

To run our application by using next framework, we should change our package.json file and add some commands in the scripts parts, just below “license”.

"scripts": {
 "dev": "next",
 "build": "next build",
 "start": "next start"
}.

This means that with some commands from the console we can actually start some operations by using yarn, just by adding of the word “run” before script.

yarn run dev

Just after the first executing of this command, as output we will not get anything and the console will show next error.

Milos Ristic Blog2 Slika2

This error is really expected and it exist just because next should have folder named pages and files inside it to use them for his own paths. In the our case, that folder doesn’t exist, and because of that we should made it ourselves into the root folder of our project. Into that folder, we should add file index.js.

In this file we should write our Next code. For now, it will be one simple sentence “Hello Next.js, I love you!”.

const Index = () => (
   <div>
       <p>Hello Next.js, I love you!</p>
   </div>
)
export default Index

If we run our application right now, with command “yarn run dev” through the console, we will get our first, simple SSR application on the address http://localhost:3000/.

Including of Express framework

Of course, the example above is not all that Next can give to us. For a little complicated SSR applications, we can combine Next with Express framework. To use Express, we must add it to our project, first.

yarn add express

After that, we create server.js file into the root folder of our project and here we’re adding next code.

const express = require('express')
const next = require('next')
 
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
 
app.prepare()
.then(() => {
 const server = express()
 
 server.set('view engine', 'ejs')
 
 server.get('*', (req, res) => {
   return handle(req, res)
 })
 
 server.listen(3000, (err) => {
   if (err) throw err
   console.log('> Ready on http://localhost:3000')
 })
})
.catch((ex) => {
 console.error(ex.stack)
 process.exit(1)
})

What’s in the code above? Firstly, we added Express and Next libraries. We set our application in the “development” mode. After that, we just prepared it and we made some routes in the Express framework. Also, we added “ejs” engine for showing files and we told server to execute on the port 3000. In the “catch” part we’re handling with some errors and we automatically exit app if errors actually exists.

In the order to use “ejs” engine for viewing content, we should add that module to the project, too.

yarn add ejs

Just after the executing “yarn run dev” command, if you’re getting this error, you can fix it easily by just adding of mime module to the project.

Milos Ristic Blog2 Slika3

yarn add mime

However, by executing “yarn run dev” command, we’re still getting that old SSR application we made by just using Next framework. Because we wish to actually execute application written by Express framework, we should change our package.json file.

Instead of

“dev”: “next”

we should write

“dev”: “node server.js”

Clean URL

Clean URL serves to get rid of bad query string in the URL. It’s really important for SEO optimization and it allow to users to use our site much easier.

URL

Clean URL

http://example.com/about.html

http://example.com/about

http://example.com/products?pid=25

http://example.com/products/25

http://example.com/p/index.php?cat=7&id=51

http://example.com/p/7/51

For clean URLs, we will use simple Express code.

server.get('/post/:title', function (req, res) {
   return app.render(req, res, '/post', { title: req.params.title})
})

If we want to be able to use this URL (e.g. http://localhost:3000/post/TitleOfPost) we must have also post.js file in the pages folder. The content of that file can be just simple title printing.

class Post extends React.Component {
   static async getInitialProps({query: {title}}) {
     console.log('TITLE', title)
     return { title }
   }
   render() {
     return <h1>This blog post title is: {this.props.title}</h1>
   }
}
export default Post

By running this application in the development mode (yarn run dev) and by visiting of the certain pages with the “post” in the front of page title, we’re dynamically change the content of the page.

Milos Ristic Blog2 Slika4

Milos Ristic Blog2 Slika5

Conclusion

SSR applications are becoming the most represented on the whole internet. Just by using Next and Express libraries, we can create big systems with Javascript, and that’s the main reason why is this stack so popular in the development’s world. Good side of writing code with these libraries is for sure that those libraries are using the most famous frameworks in the world right now, Nodejs and React.

Extra

If you found this tutorial very hard to follow, you can check out code of this example on this github link.

Share

Sign in to get new blogs and news first:

Leave a Reply

Miloš Ristić

Frontend Developer @ enjoy.ing
mm

Miloš Ristić is front-end developer with over 6+ years of experience with many front-end tools, libraries and frameworks. His skills range goes from full-stack WordPress development to mobile applications development using JS frameworks. He loves everything around JS.

Sign in to get new blogs and news first.

Categories