Next.js Quick Start Guide
eBook - ePub

Next.js Quick Start Guide

Server-side rendering done right

Kirill Konshin

Compartir libro
  1. 164 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Next.js Quick Start Guide

Server-side rendering done right

Kirill Konshin

Detalles del libro
Vista previa del libro
Índice
Citas

Información del 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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Next.js Quick Start Guide un PDF/ePUB en línea?
Sí, puedes acceder a Next.js Quick Start Guide de Kirill Konshin en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in JavaScript. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2018
ISBN
9781788995849
Edición
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...

Índice