Next.js Quick Start Guide
eBook - ePub

Next.js Quick Start Guide

Server-side rendering done right

Kirill Konshin

Condividi libro
  1. 164 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Next.js Quick Start Guide

Server-side rendering done right

Kirill Konshin

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Next.js Quick Start Guide è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Next.js Quick Start Guide di Kirill Konshin in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in JavaScript. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
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...

Indice dei contenuti