Rewriting an ExpressJS app as a NextJS app (Part 1: authentication)

Fri Feb 19 2021

After creating a web app with ExpressJS (with EJS as the template engine) and MongoDB as the database, I deployed the app to Heroku. Everything worked out except for the fact that Heroku would not let me add a domain name without www unless I got a subscription. Not wanting to pay, I decided to switch to a framework that I loved so that I can deploy it on vercel-which allows me to add any domain name I want for free without www. This also allowed me to see if I really need a MERN Stack to create a full-stack app with ReactJS or if I could just use NextJS. While I was at it, I decided to add authentication so that each user could have their own cards.


At first, I tried to use NextAuth; however, I kept on getting an error message indicating that a database is required. I tried to find a solution; however, I could not. After some time, I decided to try a different authentication method. That's when I discovered Auth0. While Auth0's easy-to-use application menu and starter kit made it easy to set up authentication, it was their documentation and login customization that won me over.

At first, I had to add the right node module for it to work with NextJS.

yarn add @auth0/nextjs-auth0

Then I needed to create a dynamic api called [...auth0].js inside a folder called auth in the api folder. inside [...auth0].js, I wrote the following:

import { handleAuth } from '@auth0/nextjs-auth0'

export default handleAuth()

In the _app.js file, I made sure it looked like this

import { UserProvider } from '@auth0/nextjs-auth0'
import '../styles/globals.css'

function MyApp({ Component, pageProps }) {

  return (
      <Component {...pageProps} />	      
export default MyApp

To ensure that users could log in/sign-up, I had to add a link to the signin page through the dynamic api [...auth0].

I did this by adding <a href="/api/auth/login">signin</a> so that users can sign in and <a href="/api/auth/logout">signout</a> so that users can sign out.

I also wanted to make sure that a user actually is logged in. To do this, I added import { useUser } from '@auth0/nextjs-auth0' to the top of my index.js page. Using the useUser function, I was able to check to see if a user was logged in by adding the following:

const {user} = useUser()

user && ? console.log("user", user) : console.log("not loggedin")

At the end of the day, I decided to change the login page so that it would look similar to the login pages in my other projects. Auth0 allowed the login page to be edited using HTML so that any web developer would be able to customize it with ease. Here's what my login page now looks like: login page