googleapis / googleapis/google-api-nodejs-client

OAuth2 globally defined client & concurrent backend function execution

Open
#2,675 1 comment 3 reactions 0 assignees View on GitHub
type: question
Dominant language
TypeScript
Stars
12.2k
Forks
2k
Avg merge
1d 9h
Merged PRs (30d)
24

Description

I have an inquiry also related to declaring oauth2Client as a variable globally in a JS file vs. locally inside a function. Replica of this Stack Overflow post I created: https://stackoverflow.com/questions/68145083/oauth2-globally-defined-client-concurrent-backend-function-execution

**START OF QUESTION:**
I have some confusion about integrating OAuth 2 flow (Google APIs) into my app. I have declared a Oauth2 client variable (globally) as shown below:

```const {gapi} = require('googleapis');
var auth2;

//Initializes the Sign-In client.
var initClient = function() {
gapi.load('auth2', function(){
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: 'CLIENT_ID.apps.googleusercontent.com'
});
// Attach the click handler to the sign-in button
auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);
});
};
```
If I were to use Google Calendar API, I would do this:
```
const doSomethingWithGCalendar = (token) => {
auth2.setCredentials({
access_token: token
});

const calendar = google.calendar({version: 'v3', auth: auth2});
// Execute some actions here
}
```

I am confused about how node.js handles this. After all, the auth2 client variable is globally declared (I picture in my head as one, single instance). However, there will be multiple users using my app, so the line .setCredentials and subsequent Google Calendar API calls will run, probably in multiple threads and concurrently, I'm assuming.

They should be running concurrently in the node.js server, but they're using the same globally declared variable auth2. How would that work ?

Should I, instead, declare a local variable inside doSomethingWithGCalendar() like this:

```
const doSomethingWithGCalendar = (token) => {
const auth2 = new OAuth2Client(
{client_id: 'CLIENT_ID.apps.googleusercontent.com'}
);
// Set Credentials/tokens and then run Google Calendar API operations ...
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.