Catch 404 urls in Next.js and write them to firebase

Piyush Sinha

By Piyush Sinha

on December 23, 2020

We recently jumped on the Jamstack bandwagon and moved our BigBinary website to use next.js. We also migrated BigBinary Blog to using next.js.

In the process of migration we knew we might have missed handling a few urls. We wanted to know all the urls which are resulting in 404 now.

Traditionally, a static site is not able to catch all the 404s. However with next.js we can capture the urls resulting in 404 and we can write those urls to firebase.

Setting up Firebase

Get Started with Firebase and create an account. Add a project there and then add a "Web app" inside that project. After that, you will find web app’s Firebase configuration something like this.

1var firebaseConfig = {
2apiKey:XXXXXXXXXXXXXXXXXXXXXXXX,
3authDomain: “test-XXXX.firebaseapp.com”,
4databaseURL: “https://test-XXXX-default-rtdb.firebaseio.com",
5projectId: “test-XXXX,
6storageBucket: “test-XXX.appspot.com”,
7messagingSenderId:00000000000,
8appId:1:00000000:web:XXXXX00000XXXXXXX9};

Edit rules in Rules section like this.

1{
2  "rules": {
3    ".read": false,
4    ".write": true
5  }
6}

Creating custom 404

To create a custom 404 page create a pages/404.js file. At build time this file is statically generated and would serve as the 404 page for the application. This page would look like this.

1import { useEffect } from "react";
2import firebase from "firebase";
3
4export default function Custom404() {
5  useEffect(() => {
6    const firebaseConfig = {
7    apiKey:XXXXXXXXXXXXXXXXXXXXXXXX,
8    authDomain: “test-XXXX.firebaseapp.com”,
9    databaseURL: “https://test-XXXX-default-rtdb.firebaseio.com",
10    projectId: “test-XXXX,
11    storageBucket: “test-XXX.appspot.com”,
12    messagingSenderId:00000000000,
13    appId:1:00000000:web:XXXXX00000XXXXXXX14    }
15
16    firebase.initializeApp(firebaseConfig).database().ref().child("404s").push(window.location.href);
17  }, []);
18
19  return <h1>404 - Page Not Found</h1>;
20}

Now all the 404s will be caught and would be written to the firebase.