google-oauth2-env-vars
v2.0.5
Published
Generate and cache Google OAuth 2.0 tokens in .env files
Downloads
1,691
Maintainers
Readme
Helper class to generate and cache Google OAuth 2.0 tokens in .env files. It generates the token of google-docs-sync and of the packages built on it.
GOOGLE_OAUTH_CLIENT_ID=23...8o1jm.apps.googleusercontent.com
GOOGLE_OAUTH_CLIENT_SECRET=QL...naxL
GOOGLE_DOCS_TOKEN={"access_token":"ya..54c","refresh_token":"1..qq0","scope":"https://www.googleapis.com/auth/documents.readonly","token_type":"Bearer","expiry_date":1598277881619}Usage
It requires Node.js 22 or later. Download the package from the npm registry:
npm install google-oauth2-env-varsGenerate .env vars
const GoogleOAuth2 = require("google-oauth2-env-vars")
const googleOAuth2 = new GoogleOAuth2({
// .env token var name
token: "GOOGLE_DOCS_TOKEN",
// Authorization scope
scope: ["https://www.googleapis.com/auth/documents.readonly"],
// APIs to enable in Google console
apis: ["docs.googleapis.com"],
//
// Optional
//
// Fixed port of the local server receiving the authorization code,
// for a "Web application" client. Any free port by default.
port: 5000,
})
const envVars = await googleOAuth2.generateEnvVars()When the variables are missing from the environment, generateEnvVars() walks you through the setup in the terminal:
- It asks you to enable each API in
apisin the Google Cloud console. - It asks for the
Client IDandClient secretof an OAuth 2.0 client of type "Desktop app". With a fixedport, it can also be a "Web application" client whose authorized redirect URI ishttp://localhost:<port>/callback. - It asks you to authorize the application, and receives the authorization code on a local server, which listens on any free port unless
portis set. The authorization uses PKCE. - It writes
GOOGLE_OAUTH_CLIENT_ID,GOOGLE_OAUTH_CLIENT_SECRETand the token to the.envand.env.*files of the current directory, or to a new.envfile when there is none. It leaves out.envrcand the templates.env.example,.env.sampleand.env.template, which are often committed. A variable that is already there is replaced.
Each URL is printed in the terminal and opened in your browser when possible.
Get Auth
getAuth() returns an OAuth2Client from google-auth-library, which refreshes the access token when it expires:
const GoogleOAuth2 = require("google-oauth2-env-vars")
const {docs} = require("@googleapis/docs")
const googleOAuth2 = new GoogleOAuth2({
// .env token var name
token: "GOOGLE_DOCS_TOKEN",
})
const auth = await googleOAuth2.getAuth()
const googleDocs = docs({version: "v1", auth})getEnvVars() returns the same variables without creating a client, and throws when one of them is missing or invalid.
