DEV Community

Cover image for Manage User Authentication in Next.js 13
Chris Achinga for Hackmamba

Posted on

 

Manage User Authentication in Next.js 13

Authentication is one of the most critical aspects of building web applications. It helps protect your users’ data and provides an extra layer of security by preventing unauthorized access. Next.js is a powerful and popular JavaScript framework for building modern web applications and it provides a server-rendered application framework and routing for progressive web applications.

This article will highlight the new Next.js features on authentication and how you can use Appwrite to implement user authentication.

Prerequisites

  • Node.js installed - It comes with Node Package Module(NPM) that is used to install and manage packages for Next.js and Appwrite web SDK
  • Docker installed - Docker is used to install Appwrite locally
  • Basic knowledge of React.js

Next.js version 13 brings enhanced features and performance including new features for implementing authentication and the ability to create protected routes by introducing a middleware to enable full flexibility with the Next.js router.

An example of a middleware for authentication is shown below:

    // middleware.js
    import { NextResponse } from "next/server"
    export function middleware(request) {
      // Clone the request headers and set a new header `x-version`
      const requestHeaders = new Headers(request.headers)
      requestHeaders.set("x-version", "13")
      // You can also set request headers in NextResponse.rewrite
      const response = NextResponse.next({
        request: {
          // New request headers
          headers: requestHeaders
        }
      })
      // Set a new response header `x-version`
      response.headers.set("x-version", "13")
      return response
    }
Enter fullscreen mode Exit fullscreen mode

To use the latest features, the code snippet shown above sending responses from middleware currently requires the experimental.allowMiddlewareResponseBody configuration option inside next.config.js

Implementing Authentication in Next.js

In Next.js version 13, authentication can be implemented in two patterns:

  • Static generation to server render loading state
  • Fetching user data on server-side

Authenticating using statically generated pages:
Next.js automatically detects static pages if the page lacks getServerSideProps and getInitialProps. This pattern ensures faster authentication because data can be served from a Content Delivery Network (CDN) and loaded using next/link.

A demo of authentication using the patterns found on GitHub.

https://github.com/vercel/next.js/tree/canary/examples/with-iron-session

Authenticating using Server Side Rendered Pages
Server-side rendered pages in Next.js have the function below:

    export async function getServerSideProps(context) {
      return {
        props: {}, // Will be passed to the page component as props
      }
    }
Enter fullscreen mode Exit fullscreen mode

Authentication Using Appwrite

Appwrite is an open-source project that provides an end-to-end solution for managing the entire lifecycle of your app, from development to deployment. It is designed to make it easy to develop, test, and deploy your app with minimal configuration.

Installing Appwrite

First, ensure that Docker is properly installed in your development environment. You can confirm the installation by running the following command on your terminal:

docker
Enter fullscreen mode Exit fullscreen mode

To install Appwrite, use the following commands based on your operating system:

Windows Command Prompt(CMD):

    docker run -it --rm ^
        --volume //var/run/docker.sock:/var/run/docker.sock ^
        --volume "%cd%"/appwrite:/usr/src/code/appwrite:rw ^
        --entrypoint="install" ^
        appwrite/appwrite:1.1.1
Enter fullscreen mode Exit fullscreen mode

Unix:

    docker run -it --rm \
        --volume /var/run/docker.sock:/var/run/docker.sock \
        --volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
        --entrypoint="install" \
        appwrite/appwrite:1.1.1
Enter fullscreen mode Exit fullscreen mode

Once the installation is complete, open a web browser and load the Appwrite server URL from the installation configurations:

localhost:<port_number>
Enter fullscreen mode Exit fullscreen mode

On loading the Appwrite on your browser, you will be redirected to a login page:

Create a new user account by clicking on the Sign Up link. After successful registration, you will be redirected to a new page to create a new project:

Enter the name of the project and proceed to create a project:

Creating a Database

You will need a database for the application. On the console menu, at the left side of the page, go to Databases and create a new Database:

After creating a Database, you will create a Collection, click on the + Create Collection button to add a user collection:

Finally, you must add attributes to store users’ emails and passwords. On the Attributes tab, create the following attributes:

    name, email, password
Enter fullscreen mode Exit fullscreen mode

Set up a Next.js Project

To set up a project using the latest version of Next.js, 13, run the following command on your command line tool:

    npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

or

    yarn create next-app
Enter fullscreen mode Exit fullscreen mode

The new version asks for a few questions, whether you want to start the project using Typescript or not and whether you want to use ESlint:

The setup uses the latest version of Next.js.

Connecting to Appwrite

To connect a Next.js application with Appwrite, install the appwrite module using:

    npm install appwrite
Enter fullscreen mode Exit fullscreen mode

Create a library file to establish the connection and use the code snippet below:

    import { Client, Account, ID } from 'appwrite';

    const client = new Client()
        .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
        .setProject('5df5acd0d48c2');               // Your project ID
Enter fullscreen mode Exit fullscreen mode

For user authentication, use Appwrite’s User API:

https://appwrite.io/docs/server/users?sdk=nodejs-default#usersCreate

To establish the connection, use the API endpoint:

    https://[HOSTNAME_OR_IP]/v1/users
Enter fullscreen mode Exit fullscreen mode

The code below is a web SDK configuration to enable email and password login:

    import { Client, Account } from "appwrite";

    const client = new Client();

    const account = new Account(client);

    client
        .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
        .setProject('5df5acd0d48c2') // Your project ID
    ;

    const promise = account.createEmailSession('email@example.com', 'password');

    promise.then(function (response) {
        console.log(response); // Success
    }, function (error) {
        console.log(error); // Failure
    });
Enter fullscreen mode Exit fullscreen mode

It starts by importing the Client and Account modules from appwrite web SDK and creates a new Client, where you set up the Appwrite endpoint and the project id.

The code then creates an email and password session:

    const promise = account.createEmailSession('email@example.com', 'password');
Enter fullscreen mode Exit fullscreen mode

Other than email and password authentication, Appwrite User’s API provides different authentication methods, including:

Conclusion

In conclusion, this post highlights how Appwrite provides an easy and secure way to manage authentication in Next.js applications. With Appwrite, developers can quickly and easily establish authentication, manage users, and provide role-based access control to their applications.

Resources

The following resources might be helpful:

Top comments (0)

Top Posts from the React Ecosystem

1. Changes In The Official React Documentation

The former React Docs Beta has been officially released as the updated React documentation at react.dev after years of hard work and refinement. Check out the brand new React Docs: What’s New in the Updated React Docs

2. CRA's Time is Over

React developer team has removed create-react-app (CRA) from official documentation rendering it no longer the default setup method for new projects. The bulky setup, slow, and outdated nature of CRA led to its removal: create-react-app is officially dead

3. How to Fetch Dev.to Articles for Your Portfolio

Integrate the articles of your Dev.to profile into your personal portfolio with either React, Vue, or Next.js by following these simple steps. It outlines how to include frontend to pull the information and correctly utilizes the Dev.to API: How to Fetch Your Dev.to Articles for Your Portfolio with React