Next.js Quick Start Guide
eBook - ePub

Next.js Quick Start Guide

Server-side rendering done right

Kirill Konshin

Partager le livre
  1. 164 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Next.js Quick Start Guide

Server-side rendering done right

Kirill Konshin

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Next.js Quick Start Guide est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Next.js Quick Start Guide par Kirill Konshin en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Programming in JavaScript. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2018
ISBN
9781788995849

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 des matiĂšres