Setting up Passport Google OAuth2.0: Possible Causes of Internal Server Error
Tags: webdev, debugging, beginners, authentication
Published: 2021-11-27 04:49:00

I have been working on a side project that builds with the MERN (MongoDB, Express, React, Node) tech stack and using [Passport.js](http://www.passportjs.org/), specifically [Google oauth2.0](http://www.passportjs.org/packages/passport-google-oauth20/). The project is deployed on Heroku (a backend application hosting cloud platform) and it is using the cloud storage database through MongoDB Atlas. 

During the set up of the passport oauth2.0, I have encountered several internal server errors that have taken some time to debug. I decided to include all the possible causes of internal server error I encountered below: 

### <em>Cause #1: ID & SECRET are not added to config vars</em>

CLIENT_ID and CLIENT_SECRET from the Google Cloud Console (should be found in the Credentials - OAuth 2.0 Client IDs - for Google Oauth API) are not added to the config vars in Heroku (or any other hosting platforms).

Config vars are similar to the variables that we placed in the .env file. They contain the secret information that we do not want the public to know for security reason. 

![Heroku Config Vars](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k078miujab5l6jckig15.png)


### <em>Cause #2: CallbackURL does not match up with the Redirect_uri</em> 

CallbackURL is the redirected url after an user is authenticated.

Redirect_uri should be added to the **Authorized redirect URIs**
in the Google Cloud Console (should be found in the Credentials - OAuth 2.0 Client IDs - for Google Oauth API). It is crucial to confirm they match up.  

```js
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: "http://www.example.com/auth/google/callback"
  }, 
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));
```

### <em>Cause #3: Routing are setup incorrectly</em> 

This is the cause that took me the longest time to debug when working on my project. Since the project is built with MERN, its frontend is using the React frontend platform, and its backend server side is using the Express Node.js web application platform.

While working in the local environment especially, if we are simply setting up the routes, we sometimes got confused between the communication of the frontend and the backend. I got stuck in this for a long period of time until I found out the correct routing setup for the communication between the frontend platform and the backend server. Please see the attempt below: 

**Local Environment** - the origin url is different when communicating between the frontend and the server. 

Frontend url: http://localhost:3000

Backend (server) url: http://localhost:3001

- __<em>Frontend (3000) ---> Backend (3001)</em>__ 
 
When signing in/signing out of an application, in the frontend, the route should be set up to communicate to the backend. So the route origin url should be set to http://localhost:3001, see example below: 

```js
//Frontend (React) main.js
//Functions to sign in/sign out of Google 
    const handleSignInGoogle = () => {
        window.open("http://localhost:3001/auth/google", "_self");     
    }

    const handleLogOutGoogle = () => {
        window.open("http://localhost:3001/auth/logout", "_self");   
    }
```
The callbackURL should be set to 3001 origin url as well:

```js
//server.js 
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: "http://localhost:3001/auth/google/callback"
  }, 
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));
```

- __<em>Frontend (3000) <--- Backend (3001)</em>__ 

Once the user is authenticated successfully, they would be redirected to a secret page (only authenticated users can access): 

```js
//server.js
app.get("/auth/google/callback", 
  passport.authenticate("google", { failureRedirect: "/login" }),
  function(req, res) {
    // Successful authentication, redirect to secret page.
    res.redirect("http://localhost:3000/secret-page");  //redirect back to the frontend secret page
  });
```

Once the user is signed out, they would be redirected to the home page:

```js
//server.js
const CLIENT_HOME_PAGE_URL = "http://localhost:3000"; 

app.get("/auth/logout", function(req, res){
    if (req.user) {
      req.session.destroy();
      req.logout();
      res.redirect(CLIENT_HOME_PAGE_URL); //redirect back to the frontend home page
    }else {
      res.send("user is already logged out!");
    }
});
```

~~

**Live Environment** - the origin url should be consistent (the same) for both the frontend and the server. 

- __<em>Frontend ---> Backend</em>__ 

```js
//main.js
    const handleSignInGoogle = () => {
        window.open("https://example.herokuapp.com/auth/google", "_self"); 
    }

    const handleLogOutGoogle = () => {
        window.open("https://example.herokuapp.com/auth/logout", "_self"); 
    }
```
```js
//server.js
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID, 
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: "https://example.herokuapp.com/auth/google/callback",   
    userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
  },
   function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));
```
- __<em>Frontend <--- Backend</em>__ 

```js
//server.js
app.get("/auth/google/callback", 
  passport.authenticate("google", { failureRedirect: "/login" }),
  function(req, res) {
    // Successful authentication, redirect to secret page.
    res.redirect("/secret-page"); 
  });
```
```js
//server.js
const CLIENT_HOME_PAGE_URL = "https://example.herokuapp.com";

app.get("/auth/logout", function(req, res){
    if (req.user) {
      req.session.destroy();
      req.logout();
      res.redirect(CLIENT_HOME_PAGE_URL);
    }else {
      res.send("user is already logged out!");
    }
});
```

### <em>Cause #4: Mongo Server Error</em>

```
MongoServerError: E11000 duplicate key error collection ... dup key: { username: null }
```
Basically it means you have already had an user with an username set to null. You can read more about this type of error [here](https://stackoverflow.com/questions/24430220/e11000-duplicate-key-error-index-in-mongodb-mongoose). 

Fastest way to resolve this error is to add an additional field - username - in the User schema (where all the users login info is stored once authenticated successfully), see example below: 

```js
const userSchema = new mongoose.Schema({
  googleId: String,
  username: String,
  fullname: String,
  firstname: String,
  profileImgUrl: String  
});


passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID, 
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    // callbackURL: "https://example.herokuapp.com/auth/google/callback", //Live 
    callbackURL: "http://localhost:3001/auth/google/callback", //Local
    userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ 
        googleId: profile.id,
        username: profile.emails[0].value,
        fullname: profile._json.name,
        firstname: profile._json.given_name,
        profileImgUrl: profile.photos[0].value
    }, function (err, user) {
      return cb(err, user);
    });
  }
));
```
### Cause #5: Mongoose-findorcreate plugin (npm package)
This is a recent cause I found in August 2022. I have been receiving the mongoose duplicate key error. Instead of getting `null`, I am getting `{username: myemailaddress@gmail.com}`. I have tried to find information online but unable to find any relevant info. 

```
MongoServerError: E11000 duplicate key error collection ... dup key: { username: myemailaddress@gmail.com }
```
When checking the [npm package](https://www.npmjs.com/package/mongoose-findorcreate), I realized the recent update of the package is a few years ago. It is kind of obsolete. I am guessing the cause of the duplicated key error could be related to this package, but I am not 100% sure. 

In order to resolve this issue, I have followed the guidance from a [blog post](https://dev.to/atultyagi612/google-authentication-in-nodejs-1f1d) to update the find or create logic as below. Using the Mongoose methods - `findOne` and `create`- this has resolved the duplicated key issue. 
```js
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID, 
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    // callbackURL: "https://example.herokuapp.com/auth/google/callback", //Live 
    callbackURL: "http://localhost:3001/auth/google/callback", //Local
    userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
  },
  function(accessToken, refreshToken, profile, cb) {
      const newUser = {
        googleId: profile.id,
        username: profile.emails[0].value,
        fullname: profile._json.name,
        firstname: profile._json.given_name,
        profileImgUrl: profile.photos[0].value
      };
      try {
        let user = await User.findOne({ googleId: profile.id });

        if (user) {
          cb(null, user);
        } else {
          user = await User.create(newUser);
          cb(null, user);
        }
      } catch (err) {
        console.log(err);
      }
  }
));
```

### Cause #6: <em>Unused or Not Needed Method</em>

This [medium article (twitter oauth using passport)](https://medium.com/free-code-camp/how-to-set-up-twitter-oauth-using-passport-js-and-reactjs-9ffa6f49ef0) is one of the references I use when setting up the Google Oauth2.0 for my side project. It is extremely helpful for beginners! 

This internal server error **was not** found while testing in the local environment until it was set live. In order to find out what causes the issue, I have used "heroku log" to find out the building process of the web application and found the issue was coming from cors method. 

As found for the live environment, there isn't a need to set up **cors** to allow the server to accept request from different origin. In the article, cors is setup for the local environment server, without any mention regarding if it is needed in the live environment. Based on what I found from my side project, <strong>cors</strong> is not needed in the live environment. 

____

There could be other possible causes of your internal server error that I might not have included in this blog post. Hopefully, this gives you some ideas regarding the possible causes of an internal server error when setting up the passport Google oauth2.0 authentication for your web application.