Search code examples
node.jsgmailnestjsgmail-apirefresh-token

Gmail send email API, Authenticate using OAuth2 without storing the refresh token in the app


I am sending emails from my NodeJS application which is working fine without any issue (using NestJS framework). The issue I am having is that I need to store the refresh token (in the .env in my case) in order to authenticate which I think is not a good approach. Because, if the refresh token is renewed my app will break and I have to manually update the refresh token every time. Is there any method to get the refresh token calling any API? any help is appreciated.

following is the code snippet I am using. I have used nestjs-modules/mailer but even with nodemailer the same issue comes.

      transport: {
        service: 'gmail',
        secure: false,
        auth: {
          type: 'OAuth2',
          user: process.env.GOOGLE_SENDER_EMAIL,
          clientId: process.env.GOOGLE_CLIENT,
          clientSecret: process.env.GOOGLE_CLIENT_SECRET,
          refreshToken: process.env.REFRESH_TOKEN,
        },
      },
      defaults: {
        from: '"ABC" <abc@gmail.com>',
      },
      template: {
        dir: join(__dirname, 'emails/templates'),
        adapter: new HandlebarsAdapter(),
        options: {
          strict: true,
        },
      },
    }),

Solution

  • Are you already implementing the Handling of the Refresh token from the NodeJS library? If so then you could consider using Domain Wide delegation and perform impersonation, this method however will require the usage of a service account in order to allow the DWD to work.