---
title: "Catch 404 urls in Next.js and write them to firebase"
description: "Catch 404 urls in Next.js and write them to firebase"
canonical_url: "https://www.bigbinary.com/blog/catch-404-urls-in-nextjs"
markdown_url: "https://www.bigbinary.com/blog/catch-404-urls-in-nextjs.md"
---

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

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

- Author: Piyush Sinha
- Published: December 23, 2020
- Categories: Next.js

We recently jumped on the [Jamstack](https://www.netlify.com/jamstack/)
bandwagon and moved our BigBinary website to use [next.js](https://nextjs.org).
We also migrated [BigBinary Blog](https://bigbinary.com/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](https://console.firebase.google.com/) 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.

```js
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.

```json
{
  "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.

```javascript
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.

## Links

- [Human page](https://www.bigbinary.com/blog/catch-404-urls-in-nextjs)
