avatarThomas Swolfs

Summary

The author shares their solution for implementing Firebase authentication in a Next.js application, including server-side rendering (SSR).

Abstract

The author discusses their experience with Next.js and Firebase authentication, highlighting the benefits of using SSR for SEO and social media sharing. They mention struggling with checking the authentication state while SSR a page and share their solution. The solution involves managing Firebase authentication with a session cookie, setting up an authentication API endpoint, and using the cookie inside the getServerSideProps method. The author also provides code examples and links to resources for further understanding.

Opinions

  • The author believes that Next.js is a great library for building React-based applications.
  • The author values the server-side rendering capabilities of Next.js for SEO and social media sharing.
  • The author thinks that Firebase is a great platform for authentication and is easy to use.
  • The author struggled with checking the authentication state while SSR a page and found a solution using session cookies and an API endpoint.
  • The author provides code examples and resources for others to learn from and improve upon their solution.
  • The author encourages feedback and discussion on their solution.
  • The author provides a link to their full code example on GitHub for further reference.

Next.js Firebase authentication— Including SSR

Lately, I’ve been playing around with Next.js. In my opinion, this is a great library to get a React-based application up and running. I was just struggling with the authentication of my application. I like to use the Firebase authentication service, so I wanted to implement this in a Next.js app.

I like to think that one of the nice features of Next JS is the server-side rendering. This allows me to perform all the required calls to my backend or database and to render a static webpage based on data retrieved by these calls. This helps with obvious things like SEO, but also for sharing webpages to social media for example. When you share a webpage on Facebook, it will crawl your page and retrieve some preview data to embed inside of the social network. When some of your data is rendered based on client-side calls, there is a big chance that Facebook will have trouble crawling your application.

Next to that, I like the fact that my end-users aren’t able to look around in my API calls. Firebase is a great platform that provides authentication for your applications. It is really easy to check the user authentications state on the client-side via Firebase. At some point, I wanted to check the authentication state while Server Side Rendering a page. I have been struggling a little to make this work.

In this article, I will show step by step how I ended up with my solution. As always, If you see any issues in my solution or if you have some interesting additions to it, feel free to comment below!

The standard example

Next.js has a lot of nice examples on their Github. Specifically, there is an example including Firebase authentication:

This is a nice example of how to use Firebase authentication, but I was always missing a part here. In this example, they are only showing how to use authentication on the client-side. Which could perfectly fit your use case.

But when I take a look at the functionalities of Next.js, the Server-Side capabilities are really interesting for me.

Particularly, the ‘getServerSideProps’ method.

Next.js gives us a PHP-like functionality in which we can handle server-side logic before rendering the page in the client. This means that you can handle some API requests or backend logic just before the user sees the page. The result of your backend logic can be passed through the ‘props’ and can be used in the frontend. This has a lot of advantages.

The issue here is, that I want to be able to retrieve the authentication state of the user. This is something that isn’t covered by the Firebase example above. I would like to share my solution with you.

The solution

So in a nutshell, what will I do?

  • Manage the Firebase authentication with a session cookie
  • Set up an authentication API endpoint, which will provide a cookie from the server-side
  • Use the Cookie inside of the getServerSideProps method.

Firebase setup

So first set up a Firebase project. Get a service account and enable email authentication. I will not explain this step into details.

One of my other stories explains this in detail:

Signing in — Client

I’m using email authentication in my example. This means you will need a form that allows the user to enter his email and password. You can find my example code in the repository at the end of the article.

We will zoom in at the utils/auth.js file:

First of all, we will set the persistence of the Firebase authentication to None. This is because we will handle this ourselves using the cookie that will be set through our API call.

In the `signIn´ method, we use the methods provided by Firebase to handle the verification of the user credentials. ‘signInWithEmailAndPassword’ does exactly what its name says.

After a successful sign-in, we perform a POST call provided by our Next.js API. In this call, we provide the IDToken we received from Firebase. Our API endpoint is going to check the validity of this token and return a response including a Cookie if the token is valid.

Signing in — API

In our pages/api/auth.js file, we will handle the incoming POST request and check for the validity of the Firebase IDToken.

If the token is valid, we will generate a Session Cookie, which will be returned through the header ‘Set-Cookie’. This will set a cookie for the client receiving the response of the call.

Please note the ‘secure’ and ‘httpOnly’ parameters, which will help to secure the cookie. Because of this, the cookie cannot be accessed via JavaScript, which protects the user for malicious third parties.

Note that the secure parameter won’t work in Localhost. That’s why I put it behind an Environment Variable. My production environment will always have this parameter set to true, but when testing locally, I will need to set this parameter to false.

Also, one of my big mistakes trying to make this work, which took me a shameful lot of my time, leaving the path parameter empty. When doing so, the path will be set to “/api” because this is the path on which the cookie is set. Because of this, I could not retrieve the cookie in the getServerSideProps method. Changing this to “/” solved this issue.

Using the Authentication state Server-side

pages/user.js:

I created a simple demo page to show how we can use the Cookie to verify the authentication.

At this point, we will know the authentication state before the page is rendered. This means that we can retrieve some user-specific data before returning HTML to the client.

utils/verifyCookie.js

This function will verify the Session Cookie with help of the Firebase SDK:

Full code example — GitHub repository

You can find the full code example on GitHub: https://github.com/ThomasSwolfs/nextjs-firebase-auth-ssr-example

I hope I can help someone out with this solution. Feel free to follow or clap if you like my content!

Cheers

Thomas

JavaScript
Nextjs
Firebase
Authentication
Software Development
Recommended from ReadMedium