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:
We explain these concepts and how to implement them in the Next.js world.
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...