Node.js quickstart

Create a Node.js command-line application that makes requests to theGoogle Apps Script API.

Quickstarts explain how to set up and run an app that calls aGoogle Workspace API. This quickstart uses asimplified authentication approach that is appropriate for a testingenvironment. For a production environment, we recommend learning aboutauthentication and authorizationbeforechoosing the access credentialsthat are appropriate for your app.

This quickstart uses Google Workspace's recommended API client librariesto handle some details of the authentication and authorization flow.

Objectives

  • Set up your environment.
  • Install the client library.
  • Set up the sample.
  • Run the sample.

Prerequisites

To run this quickstart, you need the following prerequisites:

  • A Google account with Google Drive enabled.

Set up your environment

To complete this quickstart, set up your environment.

Enable the API

Before using Google APIs, you need to turn them on in a Google Cloud project.You can turn on one or more APIs in a single Google Cloud project.
  • In the Google Cloud console, enable the Google Apps Script API.

    Enable the API

Configure the OAuth consent screen

If you're using a new Google Cloud project to complete this quickstart, configurethe OAuth consent screen. If you've alreadycompleted this step for your Cloud project, skip to the next section.

  1. In the Google Cloud console, go to Menu>Google Auth platform>Branding.

    Go to Branding

  2. If you have already configured the Google Auth platform, you can configure the following OAuth Consent Screen settings inBranding,Audience, andData Access. If you see a message that saysGoogle Auth platform not configured yet, clickGet Started:
    1. UnderApp Information, inApp name, enter a name for the app.
    2. InUser support email, choose a support email address where users can contact you if they have questions about their consent.
    3. ClickNext.
    4. UnderAudience, selectInternal.
    5. ClickNext.
    6. UnderContact Information, enter anEmail address where you can be notified about any changes to your project.
    7. ClickNext.
    8. UnderFinish, review theGoogle API Services User Data Policy and if you agree, selectI agree to the Google API Services: User Data Policy.
    9. ClickContinue.
    10. ClickCreate.
  3. For now, you can skip adding scopes. In the future, when you create an app for use outside of your Google Workspace organization, you must change theUser type toExternal. Then add the authorization scopes that your app requires. To learn more, see the fullConfigure OAuth consent guide.

Authorize credentials for a desktop application

To authenticate end users and access user data in your app, you need tocreate one or more OAuth 2.0 Client IDs. A client ID is used to identify asingle app to Google's OAuth servers. If your app runs on multiple platforms,you must create a separate client ID for each platform.Caution: This quickstart must be run locally and with access to a browser. Itdoesn't work if run on a remote terminal such as Cloud Shell or over SSH.
  1. In the Google Cloud console, go to Menu>Google Auth platform>Clients.

    Go to Clients

  2. ClickCreate Client.
  3. ClickApplication type>Desktop app.
  4. In theName field, type a name for the credential. This name is only shown in the Google Cloud console.
  5. ClickCreate.

    The newly created credential appears under "OAuth 2.0 Client IDs."

  6. Save the downloaded JSON file ascredentials.json, and move the file to your working directory.

Install the client library

  • Install the libraries using npm:

    npm install googleapis@105 @google-cloud/local-auth@2.1.0 --save

Set up the sample

  1. In your working directory, create a file namedindex.js.

  2. In the file, paste the following code:

    apps-script/quickstart/index.js
    constfs=require('fs').promises;constpath=require('path');constprocess=require('process');const{authenticate}=require('@google-cloud/local-auth');const{google}=require('googleapis');// If modifying these scopes, delete token.json.constSCOPES=['https://www.googleapis.com/auth/script.projects'];// The file token.json stores the user's access and refresh tokens, and is// created automatically when the authorization flow completes for the first// time.constTOKEN_PATH=path.join(process.cwd(),'token.json');constCREDENTIALS_PATH=path.join(process.cwd(),'credentials.json');/** * Reads previously authorized credentials from the save file. * * @return {Promise<OAuth2Client|null>} */asyncfunctionloadSavedCredentialsIfExist(){try{constcontent=awaitfs.readFile(TOKEN_PATH);constcredentials=JSON.parse(content);returngoogle.auth.fromJSON(credentials);}catch(err){returnnull;}}/** * Serializes credentials to a file compatible with GoogleAuth.fromJSON. * * @param {OAuth2Client} client * @return {Promise<void>} */asyncfunctionsaveCredentials(client){constcontent=awaitfs.readFile(CREDENTIALS_PATH);constkeys=JSON.parse(content);constkey=keys.installed||keys.web;constpayload=JSON.stringify({type:'authorized_user',client_id:key.client_id,client_secret:key.client_secret,refresh_token:client.credentials.refresh_token,});awaitfs.writeFile(TOKEN_PATH,payload);}/** * Load or request or authorization to call APIs. * */asyncfunctionauthorize(){letclient=awaitloadSavedCredentialsIfExist();if(client){returnclient;}client=awaitauthenticate({scopes:SCOPES,keyfilePath:CREDENTIALS_PATH,});if(client.credentials){awaitsaveCredentials(client);}returnclient;}/** * Creates a new script project, upload a file, and log the script's URL. * @param {google.auth.OAuth2} auth An authorized OAuth2 client. */asyncfunctioncallAppsScript(auth){constscript=google.script({version:'v1',auth});letres=awaitscript.projects.create({resource:{title:'My Script',},});res=awaitscript.projects.updateContent({scriptId:res.data.scriptId,auth,resource:{files:[{name:'hello',type:'SERVER_JS',source:'function helloWorld() {\n  console.log("Hello, world!");\n}',},{name:'appsscript',type:'JSON',source:'{"timeZone":"America/New_York","exceptionLogging":'+'"CLOUD"}',},],},});console.log(`https://script.google.com/d/${res.data.scriptId}/edit`);}authorize().then(callAppsScript).catch(console.error);

Run the sample

  1. In your working directory, run the sample:

    node .
  1. The first time you run the sample, it prompts you to authorize access:
    1. If you're not already signed in to your Google Account, sign in when prompted. If you're signed in to multiple accounts, select one account to use for authorization.
    2. ClickAccept.

    Your Nodejs application runs and calls the Google Apps Script API.

    Authorization information is stored in the file system, so the next time you run the sample code, you aren't prompted for authorization.

Next steps

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-07-02 UTC.