How to fix the gatsby firebase build issue

January 12, 2019

A post by Will Mayger
Twitter . Instagram

It’s frustrating as hell, finishing your gatsby firebase project only to find you can’t actually build it.

Thankfully the fix for this issue is actually really easy.

The reason this problem occurs, to put it simply, is that at the time of building your gatsby + firebase project gatsby does not have access to the window object which you find in the DOM, firebase needs this to work it’s magic.

So when you build this will lead you to a confusing error message that is something along the lines of WebpackError: self is not defined.

To fix the gatsby firebase build issue all you need to do is add a quick if statement in your react code to see if the window object is undefined or not. See below for a basic example of how to do this.

if (typeof window !== 'undefined') {
    // all of your firebase code in here
}

I can understand the frustration you may be having right about now because you probably haven’t built your gatsby project independently from firebase. They are probably integrated fairly deeply?

If they are, then you don’t need to worry, we can work around this with many different ways depending on how you have coded your React, gatsby, and firebase project.

First, with minimum time, effort, and patience (which is often the best for a lot of people), you could use flags and then stub your firebase methods depending on their outcome.

const flag = typeof window !== 'undefined';

let auth = null;
let db = null;
if (flag) {
    auth = firebase.auth();
    db = firebase.database();
}

export const getUser = () => (flag ? auth.currentUser : null);

Here we use a simple flag to determine the outcome of our firebase functions, without having to change the structure of our code outside of our firebase functions, saving our gatsby project.

Doing it this way is not necessarily the best way, but it is, without a doubt, one of the simplest and quickest ways because you don’t have to change any of your code outside of firebase.

This method will also work for any package, function, react component or other parts of code within your project that may use window.

The main thing to take away from this if you are building a gatsby firebase project is simply that you must check to see if the window object exists before running any firebase function or method as gatsby will not have access to the window object at the time of the build.

Hopefully this post has helped you fix your ‘WebpackError: self is not defined’ issue or any other firebase + gatsby based issue, or even any other React framework that may have similar functionality!

Will