Next.js Quick Start Guide
eBook - ePub

Next.js Quick Start Guide

Server-side rendering done right

Kirill Konshin

Share book
  1. 164 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Next.js Quick Start Guide

Server-side rendering done right

Kirill Konshin

Book details
Book preview
Table of contents
Citations

About This Book

Create, build and deploy universal JavaScript applications using Next.js

Key Features

  • Work with the entire tool-chain for developing universal Javascript applications with Next.js
  • A straightforward guide to implementing server-side rendering
  • Use Next.js to build SEO-friendly and super fast websites

Book Description

Next.js is a powerful addition to the ever-growing and dynamic JavaScript world. Built on top of React, Webpack, and Babel, it is a minimalistic framework for server-rendered universal JavaScript applications. This book will show you the best practices for building sites using Next. js, enabling you to build SEO-friendly and superfast websites.

This book will guide you from building a simple single page app to a scalable and reliable client-server infrastructure. You will explore code sharing between client and server, universal modules, and server-side rendering.

The book will take you through the core Next.js concepts that everyone is talking about – hot reloading, code splitting, routing, server rendering, transpilation, CSS isolation, and more. You will learn ways of implementing them in order to create your own universal JavaScript application. You will walk through the building and deployment stages of your applications with the JSON API, customizing the confguration, error handling, data fetching, deploying to production, and authentication.

What you will learn

  • Explore the benefts of server-side rendering with Next.js
  • Create and link JavaScript modules together by understanding code splitting and bundling
  • Create website pages and wire them together through website navigation
  • Extend your application with additional Webpack loaders and features, as well as custom Babel plugins and presets
  • Use GraphQL and Apollo frameworks with Next.js to fetch data and receive push notifcations
  • Design and implement core modules, such as logging and authentication, and then more complex solutions for access control and business rule management
  • Write tests and use online CI tools such as Travis, GitLab, and more
  • Build a Docker-based container for your app and deploy it to online services such as Heroku and Now.sh

Who this book is for

This book is for JavaScript developers who want to learn how to generate server-rendered applications.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Next.js Quick Start Guide an online PDF/ePUB?
Yes, you can access Next.js Quick Start Guide by Kirill Konshin in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in JavaScript. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781788995849
Edition
1

Application Life Cycle Handlers and Business Logic

Now, since we have learned all the basic stuff and we know how to use Next.js for everyday coding, we can move on to more complicated things, which are more about application architecture.
This chapter is not that much about Next.js, but it covers the most important and frequently asked questions about React-based app architecture and patterns. We explain how to design and implement the core concepts and more complex solutions:
  • Authentication
  • Role-based access control
  • Business rule management
  • Internationalization
  • Error handling
  • Caching
  • Analytics
We explain these concepts and how to implement them in the Next.js world.

Authentication

Almost any application requires at least a very basic distinction between known users and guests, for example, to allow known users to store some of their information (such as their settings) in persistent storage on the backend side. It is quite obvious that users will want to access their data from anywhere, so we must fulfill this requirement.
Since the purpose of this book is a deep dive into Next.js, we will show how React and authentication best practices can be integrated specifically with Next.js.
But before we get started with the code, let's analyze the nature of the authentication process. It consists of several important aspects:
  • Persistent storage of user credentials
  • A method to send credentials to the server from the client side
  • A check that finds the user and verifies the entered credentials
  • A mechanism that signs all user requests so that the server can identify who is requesting what
  • A mechanism that allows the user to sign out
For this example, we will take the static config of users, but API-wise we are going to build a system that should not care about the source of such data. For client-server interaction, we will use Redux and fetch as before. The check will be a simple function that verifies login and password. We will use cookies to sign requests as it's the simplest way to add something to all requests that go to the server.
Since we will be using custom server-side endpoints for login/logout, we will take the server example from an earlier chapter.
Let's start with the users server-side API. We will need a few packages:
$ npm install uuid lodash --save-dev
The idea of the login process will be quite straightforward: for each successful login attempt, we will create a UUID and attach it to the user so if this UUID is used to sign a request, we will be able to recover the user info from it.
Now, let's make the API:
const uuid = require('uuid/v4');
const find = require('lodash/find');

const users = [
{username: 'admin', password: 'foo', group: 'admin'},
{username: 'user', password: 'foo', group: 'user'},
];

const tokens = {};

const findUserByUsername = (username) => find(users, {username});

const findUserByToken = (token) => {
if (!(token in tokens)) throw new Error('Token does not exist');
return users[tokens[token]];
};
Here, we have created a static "DB"s of users and tokens. We have added two functions that allow us to find users by username and by token.
Now, let's use those function to perform the login procedure:
const login = (username, password) => {

const user = findUserByUsername(username);

if (!user) throw new Error('Cannot find user');

if (user.password !== password) throw new Error('Wrong password');

const token = uuid();

tokens[token] = users.indexOf(user);

return {
token,
user
};

};
We attempt to find a user by username, and if that's successful, we compare the stored password and provided one. If this check is also successful, then we create a new token (UUID) and establish a relationship between token and user by creating an entry in the token storage. After that, we cut out sensitive user information and return the result.
Let's add the logout procedure:
const logout = (token) => {
delete tokens[token];
};
This simple function deletes the token from storage; this makes sure that the token is useless and no users will be located based on it.
Here is the final API file:
// users.js
const uuid = require('uuid/v4');
const find = require('lodash/find');

const users = [
{username: 'admin', password: 'foo', group: 'admin'},
{username: 'user', password: 'foo', group: 'user'},
];

const tokens = {};

const findUserByUsername = (username) => find(users, {username});

const findUserByToken = (token) => {
if (!(token in tokens)) throw new Error('Token does not exist');
return users[tokens[token]];
};

const login = (username, password) => {

const user = findUserByUsername(username);

if (!user) throw new Error('Cannot find user');

if (user.password !== password) throw new Error('Wrong password');

const token = uuid();

tokens[token] = users.indexOf(user);

return {
token,
user
};

};

const logout = (token) => {
delete tokens[token];
};

exports.findUserByUsername = findUserByUsername;
exports.findUserByToken = findUserByToken;
exports.login = login;
exports.logout = logout;
We have to install a few packages to enable the request parsing functionality of Express:
$ npm install express body-parser cookie-parser --save-dev
Now, we can make the server:
// server.js
const express = require('express');
const next = require('next');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

const port = 3000;
const cookieName = 'token';
const dev = process.env.NODE_ENV !== 'production';
const app = next({dev});
const handle = app.getRequestHandler();
const server = express();

server.use(cookieParser());

server.use(bodyParser.json());

server.get('*', (req, res) => {
return handle(req, res);
});

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

server.listen(port, (err) => {
if (err) throw err;
console.log('NextJS is ready on http://localhost:' + port);
});

}).catch(e => {

console.error(e.stack);
process.exit(1);

});
Now, let's add an endpoint that will use an API method to log the user in, and if it's successful, it will set a cookie with the newly created token:
const cleanupUser = (user) => {
const newUser = Object.assign({}, user);
delete newUser.password;
return newUser;
};

server.post('/api/login', (req, res) => {

try {

console.log('Attempting to login', req.body);

const authInfo = users.login(req.body.username, req.body.password);
authInfo.user = cleanupUser(authInfo.user);

res.cookie(cookieName, authInfo.token, {
expires: new Date(Date.now() + 1000 * 60 * 60 * 24),
httpOnly: true
});
res.send...

Table of contents