Search code examples
node.jsgoogle-apigmail-apipm2

Gmail API Nodejs and PM2 authentication


I have set up code to send emails using Gmail API in Nodejs. It works perfectly well in local machine. It asks to enter a code by visiting URL. Something like,

Authorize this app by visiting this URL: someURL
Enter the code from that page here: copy-paste code here

This is automatically done by Google following Node.js Quickstart for Gmail and it automatically generates token.json. Everything works perfectly fine in development.

Now in production, I deploy my app using PM2 and Nginx. So, now each node server is running in background and logs are generated in files.

I see the above prompt in the log file Enter the code from that page here:. But as the log is piped to the file, I have no way of pasting the code since I don't have access to standard input.

I have tried generating token.json from local and using it in the server which doesn't seem to work.

How do I fix this and is there any way around this?

NOTE: The code to authorize and send mails works just fine. I'm not posting it here because I don't want the question to be cluttered.


Solution

  • If you are trying to make a server application without need of user interaction instead of using regular OAuth you could try to use Service Account.

    Although take into account that service accounts don't have the Gmail API per se, so you should enable the Domain-Wide Delegation to impersonate another user of the domain.

    If you insist in authenticating a real user, you can retrieve the token.json before implementing PM2 and using it afterwards.

    Also you can take a look at these two (1 and 2) github posts that also opens your initial thought of trying to use the stdin to authenticate the user.