Reader small image

You're reading from  Real-World Next.js

Product typeBook
Published inFeb 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781801073493
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Michele Riva
Michele Riva
author image
Michele Riva

Michele Riva is a passionate and experienced Software Engineer and Google Developer Expert from Milan, Italy. During the last years, he has contributed to many open-source projects from big companies and foundations, such as Facebook and Apache, in many different programming languages and paradigms, including Haskell, Erlang, Go, and JavaScript. He has also written dozens of public domain articles on different topics (software architecture, functional programming, performance enhancements, etc.) and gave many talks at conferences and meetups. He is currently working as a Senior Software Engineer in the architecture team at ViacomCBS, where he is building a multi-tenant Node.js application at the heart of their websites and streaming services.
Read more about Michele Riva

Right arrow

Chapter 12: Managing Authentication and User Sessions

In the previous chapters, we've seen how to work with some of the fundamental Next.js features. We learned how to choose between rendering strategies and how those can influence SEO and performance. We also learned how to style our application using built-in and external styling methods and libraries, managing the application state, integrating with external APIs, and many other valuable things.

Starting with this chapter, we will begin to learn and develop real-world applications by combining the lessons learned in the past sections with industry-standard strategies to keep our applications secure, performant, and highly optimized in every aspect.

In this chapter, we will see how to manage user session and authentication, an essential part of every highly dynamic web application.

We will cover the following topics in detail:

  • How to integrate our application with a custom authentication service
  • How to...

Technical requirements

To run the code examples in this chapter, you need to have both Node.js and npm installed on your local machine. If you prefer, you can use an online IDE such as https://repl.it or https://codesandbox.io; they both support Next.js, and you don't need to install any dependency on your computer. As for the other chapters, you can find the code base for this chapter on GitHub: https://github.com/PacktPublishing/Real-World-Next.js.

A brief introduction to user sessions and authentication

When talking about user authentication, we refer to that process that identifies a specific user, letting them read, write, update, or delete any protected content, depending on their authorization level.

A typical example could be a simple blogging system: we can publish, edit, or even delete content only after authenticating ourselves.

There are many different authentication strategies, but the most common are:

  • Credentials-based authentication: This method allows us to log in to a system using personal credentials, commonly, an email address and a password.
  • Social login: We can log in to a system using our social accounts (Facebook, Twitter, LinkedIn, and so on).
  • Passwordless login: Over recent years, this has become a pretty popular authentication method. Platforms such as Medium and Slack will send you what's called a "magic link" to your email address, letting you enter your account without...

Understanding JSON web tokens

As written on the https://jwt.io website, a JWT (short for JSON Web Token) is an open, industry-standard RFC 7519 method for representing claims securely between two parties.

To keep it simple, we can think of JWTs as three distinct base64-encoded JSON chunks of data.

Let's take the following JWT as an example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5MDhlYWZhNy03MWJkLTQyMDMtOGY3Ni1iNjA3MmNkMTFlODciLCJuYW1lIjoiSmFuZSBEb2UiLCJpYXQiOjE1MTYyMzkwMjJ9.HCl73CTg8960TvLP7i5mV2hKQlSJLaLAlmvHk38kL8o

If we pay enough attention, we can see three different chunks of data separated by periods.

The first part represents the JWT header. It contains two essential pieces of information: the token type and the algorithm used for signing it (we will talk more about that in just a second).

The second part is the payload. Here is where we put all the non-sensitive data that can help us identify our users. Never store data such as passwords and...

Custom authentication – the good, the bad, and the ugly

Let's make this clear from the outset: when possible, we should avoid implementing custom authentication strategies. There are several great providers (including Auth0, Firebase, AWS Cognito, and Magic.link, just to name a few) that are putting a lot of effort into making authentication secure, reliable, and optimized for many different situations. When investigating authentication strategies for a web app, I'd highly recommend looking into a well-established service provider as this is possibly one of the most critical aspects of a dynamic web application.

In this section, we're looking into creating a custom authentication mechanism for a simple reason: we just want to understand at a high level how authentication works, how to make it as secure as possible, and what the critical factors of a custom auth system are.

As we'll find out during this section, there will be several limitations when...

Implementing authentication using Auth0

In the previous section, we've seen how to implement an elementary and straightforward authentication method. I won't repeat this enough: what we saw was just a high-level overview and shouldn't be used for any production-ready product.

When building production-ready web apps, we're likely to adopt external authentication methods, which are secure and reliable.

There are many different auth providers (AWS Cognito, Firebase, Magic.link, and so on), and I believe they're all doing a fantastic job protecting their users. In this chapter, we will be using a popular, secure, and affordable authentication provider, taking advantage of its generous free plan: Auth0.

If you want to follow along with this chapter, you can create a free account on https://auth0.com (no credit card is required for free plan users).

Auth0 will manage the most complex steps of any authentication strategy and will give us some friendly...

Summary

In this chapter, we've seen how using a third-party authentication provider can save us from many issues when dealing with complex and sensitive topics such as private data management and user sessions.

So, the final question could be: when does it make sense to implement a custom authentication strategy? In my humble opinion, we should avoid writing custom authentication mechanisms in almost any scenario, unless we're working with an expert team capable of detecting security flaws and identifying vulnerabilities in the whole authentication flow.

There are many good alternatives to Auth0 (NextAuth.js, Firebase, AWS Cognito, and so on), and it is just too risky to replicate their battle-tested features.

If you're not comfortable working with external providers, you can also use any web framework and its built-in authentication strategies. For example, suppose you feel comfortable using Ruby on Rails, Laravel, or Spring Boot. In that case, these are all...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Real-World Next.js
Published in: Feb 2022Publisher: PacktISBN-13: 9781801073493
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Michele Riva

Michele Riva is a passionate and experienced Software Engineer and Google Developer Expert from Milan, Italy. During the last years, he has contributed to many open-source projects from big companies and foundations, such as Facebook and Apache, in many different programming languages and paradigms, including Haskell, Erlang, Go, and JavaScript. He has also written dozens of public domain articles on different topics (software architecture, functional programming, performance enhancements, etc.) and gave many talks at conferences and meetups. He is currently working as a Senior Software Engineer in the architecture team at ViacomCBS, where he is building a multi-tenant Node.js application at the heart of their websites and streaming services.
Read more about Michele Riva