When the person responsible for website content isn't technical, handing off edits to developers indefinitely doesn't scale, and pulling in a full CMS like WordPress adds a new platform to learn, a new attack surface, template syntax, and plugins to vet. Google Drive offers a different path: content lives in the docs the team already uses, and the site pulls it out through the Drive API with a simple REST request. This walkthrough covers authentication, fetching docs and sheets, server-side caching, and wrapping it all in an Express service. A companion Git repo, npm package, Docker image, and demo are available throughout.

Why a service account instead of OAuth

The Drive API requires authentication even when files are publicly link-shared. The usual OAuth flow is a poor fit here: it prompts a Google-branded consent screen for access to the *user's* drive, when the goal is a single central drive, and scoping to specific files or folders is awkward. The https://www.googleapis.com/auth/drive.readonly scope is described on the consent screen as:

See and download all your Google Drive files.

That's alarming to users and a real security weakness on a central admin account: anything that account can reach — its own documents and anything shared with it — would be exposed through the CMS back end.

A Google service account avoids this. It's effectively a dummy account for APIs and bots, but behaves like a first-class one: its own email address, its own authentication tokens, its own permissions. Files reach it the same way they reach any user — by sharing them with that email address.

[email protected]

To put a doc or sheet on the site, you hit "Share" and paste in the address. The service account sees only what has been explicitly shared, and that access can be changed or revoked at any time.

Service accounts are created for free in the Google Cloud Platform Console; Google documents the process in its developer resources, and the companion repo's README walks through it step by step. From there, the setup starts from a modified Node.js quickstart sample. The key change is in authorize(), which uses a jwtClient instance instead of Google's oauthClient.

authorize(credentials, callback) {
  const { client_email, private_key } = credentials;

  const jwtClient = new google.auth.JWT(client_email, null, private_key, SCOPES)

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return this.getAccessToken(jwtClient, callback);
    jwtClient.setCredentials(JSON.parse(token.toString()));
    console.log('Token loaded from file');
    callback(jwtClient);
  });
}

This code runs server-side only. The service account credentials must never reach site visitors: they sit in credentials.json on the server, are loaded with fs.readFile, and are listed in .gitignore to keep them out of source control.

Reading docs and sheets

Docs to HTML

With authentication in place, pulling raw HTML out of a Google Doc is simple. A method returns a Promise of an HTML string:

getDoc(id, skipCache = false) {
  return new Promise((resolve, reject) => {
    this.drive.files.export({
      fileId: id,
      mimeType: "text/html",
      fields: "data",
    }, (err, res) => {
      if (err) return reject('The API returned an error: ' + err);
      resolve({ html: this.rewriteToCachedImages(res.data) });
      // Cache images
      this.cacheImages(res.data);
    });
  });
}

The Drive.Files.export endpoint does the work. The id is the string in the browser's address bar right after https://docs.google.com/document/d/. The two image-caching lines are covered below. A sample page shows a Google document rendered as HTML this way.

Sheets to JSON

Sheets are nearly as easy via Spreadsheets.values.get. The response is adjusted slightly into a simplified JSON array whose keys come from the first row's column headers.

getSheet(id, range) {
  return new Promise((resolve, reject) => {
    this.sheets.spreadsheets.values.get({
      spreadsheetId: id,
    range: range,
  }, (err, res) => {
    if (err) return reject('The API returned an error: ' + err);
    // console.log(res.data.values);
    const keys = res.data.values[0];
    const transformed = [];
    res.data.values.forEach((row, i) => {
      if(i === 0) return;
      const item = {};
      row.forEach((cell, index) => {
        item[keys[index]] = cell;
      });
       transformed.push(item);
      });
      resolve(transformed);
    });
  });
}

The id is the same as for a doc; the new range parameter selects the cells to read in Sheets A1 notation. The companion demo includes a page that reads and parses a published Sheet to render custom HTML.

Those two endpoints form the backbone of a custom CMS, but they only scratch the surface. The Drive API can also list files in a folder for a menu, import media from a Google Slides presentation, and download and cache custom files. The constraints are the full Drive API itself.

Caching: rate limits and hotlinked images

Repeated trial-and-error during development can easily produce a "User Rate Limit Exceeded" error, which looks like a hard blocker for the whole approach. Server-side caching solves it. Each time a new *version* of a Drive file is fetched, it's cached locally inside the Node.js process. After that, only the file's *version* needs checking — a stale cache triggers a fetch of the newest version, and that request happens once per file version rather than once per user request. Scaling is then tied to the number of edits on Drive instead of the number of site visitors. On a free-tier account's usage limits, that's up to 300 API requests per minute; caching should stay well inside it, and batching requests can optimize further.

Images are cached too

The same method applies to images embedded in Docs. getDoc parses the HTML response for image URLs, makes a secondary request to download each one (or takes it from cache if present), and rewrites the original URL in the HTML. The site never hotlinks Google's image CDNs — by the time HTML reaches the browser, the images are already pre-cached.

Caching buys two things. It keeps usage of Google's APIs to the minimum needed to refresh the cache — using Drive as the editing and file-management front end it's meant to be, rather than as free bandwidth and storage. And it gives visitors a fast site: cached Docs are static HTML on your own server, fetched immediately rather than waiting on a third-party request.

Exposing it with Express

Because all of this is server-side Node.js, client pages need a way in. Wrapping DriveAPI in its own REST service creates a proxy that hides the caching and version-fetching logic while keeping credentials on the server. A set of express routes — or the equivalent in another server — does the job:

const driveAPI = new (require('./driveAPI'))();
const express = require('express');
const API_VERSION = 1;
const router = express.Router();

router.route('/getDoc')
.get((req, res) => {
  console.log('GET /getDoc', req.query.id);
  driveAPI.getDoc(req.query.id)
  .then(data => res.json(data))
  .catch(error => {
    console.error(error);
    res.sendStatus(500);
  });
});

// Other routes included here (getSheet, getImage, listFiles, etc)...

app.use(`/api/v${API_VERSION}`, router);

The full express.js file is in the companion repo.

Deployment

In production, the Express server can run alongside your static web server, or be wrapped in Docker:

FROM node:8
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN npm install
# If you are building your code for production
# RUN npm ci --only=production
# Bundle app source
COPY . .
CMD [ "node", "express.js" ]

A pre-built image is also published on Docker Hub.

Internal sites: adding Google sign-on with NGINX

A public-facing site needs nothing more. For an internal-only documentation site, Link Sharing is turned off on every Google Doc (kept in an isolated, dedicated Google Team Drive separate from company content), and the extra security layer goes in at the server level, before requests reach Express or static content. NGINX intercepts and reverse-proxies everything using Cloudflare's nginx-google-oauth Docker image, presenting a Google sign-on screen to all employees for every resource and endpoint. It integrates with the corporate Google single-sign-on, so no additional account is required.

When this architecture fits

This is a lightweight, decentralized CMS: raw data stays in Drive, where the team already works, with a familiar UI, while the front end keeps the full presentation control of pure HTML and CSS. The developer does some extra legwork; non-dev collaborators and end users see a seamless experience. It won't suit every site, but it fits these cases:

  • An internal site with a few hundred to a few thousand daily users. Even one metadata request per user on a global company homepage could approach the Drive API limit. Further techniques can mitigate that, but small to medium sites are the sweet spot.
  • A single-page app. This setup queries the version of every data source in one REST request, once per session rather than once per page. A non-SPA could do the same with cookies or local storage, at the cost of extra work.
  • A team already on Google Drive. Collaborators can contribute through an account and workflow they already use and are comfortable with, including Google's WYSIWYG editing and access management.