Introduction
This article will cover email-based authentication basics using Next.js and Altogic, a backend-as-a-service platform using its client library. This authentication method requires users to specify their email and passwords during sign-up. After signing up, users can log in to the application using their email and password. You can check the source code and demo app.
By default, email verification is enabled in your App settings → Authentication view of Altogic Designer. If you would like to change this, you can disable “Confirm email addresses” in the Authentication view of Altogic Designer.
How is the email authentication flow in Altogic?
- Users sign up with their email and password.
- A verification email is sent to the specified email address by Altogic.
- Users confirm their email by clicking on the link in the sent email.
- Altogic checks the token in clicked link and if valid changes the user’s email address to verified and returns an access token in the query string parameter of the redirect URL.
- This access token is used to get a session token and users are directed to their profile page.
Youtube Promo Video
You can check out the video below to see a live demonstration of our app.
Set up the backend
Create an app in Altogic
First things first: To use Altogic, we need to create an app in Altogic. We can create an app in Designer easily. All you need to do is enter a name for your app.
We need envUrl
and clientKey
to access our environment via Altogic Client Library. envUrl
is specific to each environment, and Altogic initially creates one environment for you when you create your app. Here is how to get the envUrl
from environment details page.
We can get the clientKey
by clicking on the App Settings button in the left-bottom corner of the Designer and clicking on the Client library keys section.
Users model
By default, Altogic creates a user model for you. You can customize it by adding different fields. Some of them are pretty advanced and customized, which is very handy.
Set up the Frontend
Install the packages
Before you start to use the npx
command, make sure you have NodeJS installed in your development environment. Also, installing VSCode and some extensions might be better for faster development.
💡 You can visit https://nodejs.org/en/download/ to download.
To get started, open the terminal and create a new Next.js project.
npx create-next-app@latest
Next.js will ask you to name the project. Name it whatever you want; I will use “altogic-email-authentication” for this example. Move to the folder just created and install the Altogic Client Library.
cd altogic-email-authentication
npm i altogic
Open the project in VSCode.
Install tailwind CSS and create tailwind.config.js
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Add the paths to all of your template files in your tailwind.config.js
file.
Add the following directives to your globals.css
file.
Install Font Awesome to use the icons.
npm i --save @fortawesome/fontawesome-svg-core
npm install --save @fortawesome/free-solid-svg-icons
npm install --save @fortawesome/react-fontawesome
npm i @fortawesome/free-brands-svg-icons
Install cookies-next to set cookies for server-side rendering easily.
npm i cookies-next
Install @headlesui/react for styling.
npm i @headlessui/react
Update the next.config.js
file to allow the Next.js Image component to load images from Altogic’s storage. "c1-na.altogic.com"
value is retrieved from the envUrl
which starts with c1-na.altogic.com
in my case.
Set up the environment variables
Environment variables are used to secure your secret keys, reuse them in different places and reduce production mistakes. Create a .env.localfile
in the root directory of your application, open the file in your editor and paste the following. You can check more about environment variables in Next.js here.
Replace YOUR-APPLICATION-ENV-URL
and YOUR-APPLICATION-CLIENT-KEY
with the envUrl
and clientKey
values you retrieved while setting up your backend.
Next, create a file to create the Altogic Client Library instance.
mkdir helpers
cd helpers
touch client.js
This creates a client.js
file in the helpers directory. Open the file in your editor and paste the following.
Here, you need to enter the envUrl
and clientKey
. Optionally you can paste signInRedirect
to redirect your users to the specified sign-in page in some cases. This works in a way that if users try to perform a session-required action while their session has been destroyed, Altogic redirects them to the signInRedirect
route.
Building our components
The next step is to create the components we’ll need for our application. You can also clone our example repository and use the components right away.
First, create a components folder with the mkdir components
command. Let me walk you through the components we use for our app.
-
Sign-in.js
andSign-up.js
file inauth
directory. Those are the form components we use to sign-up and sign in our users. -
EmailConfirmResend.js
andPasswordReset.js
file inauth-redirect
directory. Those are the components we will show our users when redirected to the our-domain.com/auth-redirect route. -
AltogicBadge.js
,Header.js
andLayout.js
file inlayout
directory. Those are the components we use for our layout throughout the app. -
SessionListItem.js
,SessionList.js
,ProfilePhoto.js
,NameSection.js
,ChangePassword.js
andChangeEmail.js
file inprofile
directory. Those are the components we use on the profile page. -
Button.js
,Notification.js
andErrorMessage.js
file inui
directory. Those are the components we use many times to build our UI.
In the end, your components folder should look like this:
Let’s start coding!
We have the backend and frontend setup ready. We can start integrating them now.
Some UI components we use often
It is best to separate the logic of some of the components we use frequently and put them into a different folder to reuse.
Button:
Error:
Sign up functionality with Altogic
Altogic Client Library has a built-in function for creating new users with an email and password. You can check about it more here.
altogic.auth.signUpWithEmail takes three inputs:
- email (mandatory)
- password (mandatory)
- name (optional) The code snippet handles the form input using the signUpWithEmail function.
Our sign-up screen should look like this:
This function will create a user object in your database with the provided email, password, and optionally name field. Altogic will send an email to the user’s email address.
Redirect URL route
In Altogic, you can redirect your users to a predefined route for some actions.
- When the user is successfully authenticated using an oAuth provider or a magic link, they will be redirected here.
- When the email confirmation link is clicked, they are redirected to this route.
- When a user changes their email, if the email confirmation setting of the app is enabled, an email is sent to them. After the user clicks it, they will be redirected to this route.
- When a user recovers their password, they are redirected to this route.
You can check and edit this route from Designer like below.
Here in getServerSideProps, we check the query string parameters and according to each action, we perform some actions. Here is an important part!
getAuthGrant()
function either takes a session token as a parameter or uses the one in the URL.
In the example below, Altogic sent the user an email confirmation mail. When clicked, it redirects to our specified Redirect URL, which is auth-redirect.
There are three query parameters:
- status=200 indicates that Altogic managed to send me a valid token for my operation.
- access_token gives us the token value I am going to use.
- action=email-confirm indicates for which action I am going to use this token. In this case, it is confirming my email.
Here, we run this code only on the server-side, so we must give the session token as the parameter.
Sign in functionality with Altogic
Altogic Client Library also has a built-in function for signing in users. You can check about it more here. The code snippet handles the form input using the signInWithEmail function.
altogic.auth.signInWithEmail takes two inputs:
- email (mandatory)
- password (mandatory)
As you can see in the code above, we are sending a POST request to /api/login route. We are doing this to set the cookie for server-side rendering (SSR). If you are not going to use SSR, you can delete these lines.
Why do we need cookies for SSR?
One of the key features of Next.js is server-side rendering. Meaning that some of the code will run only on the server and not on the client side. But session and user information is stored on the client-side. How do we understand if we have a user authenticated when a request is made to the server? For this purpose, we need to set a cookie on the server-side when we sign in and delete it when we sign out. This way, we can check if the user is authenticated on the server-side and then perform the actions we want.
Here is the code you need to add to your api/login folder:
On any page, we can check if there is a user signed in or not. This part is needed both for route protection and fetching data special to the user with SSR.
Our sign-in screen should look like this:
How to check if there is a user authenticated via SSR?
getServerSideProps function runs every time the user makes a request. It runs only on the server, and its content is not exposed to the client. We check if a user is authenticated and redirect them to their profile or sign-in page accordingly.
Signout users
Here is the page you can redirect your users to log them out. It simply invalidates the session, clears the context, and sends a POST request to our-domain/api/logout to clear the cookies.
When we sign out, we need to delete the cookie we set on the server-side because the token value in the cookie is no longer valid.
Here is the code you need to add to your api/logout file:
Storing user information in context
The UserContext
creates a context and sets the user and session property null by default. To learn more about context and how to effectively use them, read React’s documentation on context.
More features
Our example application covers more features like uploading a profile picture, managing sessions, password recovery, password change, and email change. You can check all of them in the repository. Here, I just want to show you how easily you can implement them with client library functions.
Conclusion
In this article, we built a simple yet capable email authentication app using Next.js and Altogic Client Library. Generally, building authentication is one of the most challenging parts of app development. Thanks to Altogic, we can build this functionality with just a few lines of code.
You can check out the GitHub repository for other functionalities and the rest of the code. You can also clone it and build your app on top of it.
Top comments (0)