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

Piyush Sinha

Piyush Sinha

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.

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

Edit rules in Rules section like this.

{
  "rules": {
    ".read": false,
    ".write": true
  }
}

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.

import { useEffect } from "react";
import firebase from "firebase";

export default function Custom404() {
  useEffect(() => {
    const firebaseConfig = {
    apiKey: “XXXXXXXXXXXXXXXXXXXXXXXX”,
    authDomain: “test-XXXX.firebaseapp.com”,
    databaseURL: “https://test-XXXX-default-rtdb.firebaseio.com",
    projectId: “test-XXXX”,
    storageBucket: “test-XXX.appspot.com”,
    messagingSenderId: “00000000000”,
    appId: “1:00000000:web:XXXXX00000XXXXXXX”
    }

    firebase.initializeApp(firebaseConfig).database().ref().child("404s").push(window.location.href);
  }, []);

  return <h1>404 - Page Not Found</h1>;
}

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

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.