Node.js Gmail API Service Account Returns Bad Request Error

I’m trying to build a Node.js application that automatically fetches emails from Gmail without user authentication. I want to display newsletter emails publicly when users visit my page.

app.get("/newsletters", async (req, res) => {
    const credentials = require('../service-account.json');
    const authClient = new google.auth.JWT(
      credentials.client_email,
      null,
      credentials.private_key,
      ['https://www.googleapis.com/auth/gmail.readonly'],
      null
    );

    try {
      await authClient.authorize();
      const gmail = google.gmail({version: 'v1', auth: authClient});
      
      const response = await gmail.users.messages.list({
        userId: 'me',
        maxResults: 10
      });
      
      res.json(response.data);
    } catch (error) {
      console.error('API Error:', error);
      res.status(500).send('Failed to fetch emails');
    }
});

However, I keep getting a failedPrecondition error with “Bad Request” message. I read that service accounts might only work with Google Workspace accounts, not personal Gmail accounts.

Is this limitation real? If so, what alternatives exist for automatically accessing Gmail messages without OAuth flow? I need the API to work immediately when someone visits the page.

yep, that’s a bummer. service accounts only play nice with google workspace, so for regular gmail, oauth is your only option. you might wanna consider using imap tho? it’ll let you connect to gmail’s servers directly, but make sure app passwords are enabled.

You’re right about the service account limitation - Google only allows them with Workspace domains, not personal Gmail. But there’s a solid workaround. Set up OAuth2 once and grab a long-lived refresh token, then store it securely. After that initial manual OAuth flow, your app can pull emails automatically using the refresh token to get new access tokens. You could also try Gmail’s push notifications with Pub/Sub for real-time email updates, though you’ll still need OAuth setup first. IMAP works too, but OAuth tokens are usually more reliable and secure for production stuff.

I faced a similar issue when working on a project where I needed to automate email fetching. You are correct that service accounts are limited to Google Workspace; I spent significant time troubleshooting this before realizing it. Ultimately, I used OAuth2 along with refresh tokens, which I stored securely to avoid repeated authentication processes. If your project permits, consider creating a Google Workspace account for seamless access. The documentation can indeed be confusing, so it’s understandable to run into this problem. Once set up, refresh tokens will serve well for continual access without the need for user interaction.