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 = {
3authDomain: “”,
4databaseURL: “",
5projectId: “test-XXXX,
6storageBucket: “”,

Edit rules in Rules section like this.

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

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";
4export default function Custom404() {
5  useEffect(() => {
6    const firebaseConfig = {
8    authDomain: “”,
9    databaseURL: “",
10    projectId: “test-XXXX,
11    storageBucket: “”,
12    messagingSenderId:00000000000,
13    appId:1:00000000:web:XXXXX00000XXXXXXX14    }
16    firebase.initializeApp(firebaseConfig).database().ref().child("404s").push(window.location.href);
17  }, []);
19  return <h1>404 - Page Not Found</h1>;

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

If you liked this post, see our full blog archive.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.