Build a "similar books" widget in JavaScript
This tutorial adds a row of six similar books, with covers and titles, to a book page. It has two parts: a Node.js proxy of about 80 lines that calls Big Book API with your key, and a front-end script that fetches the proxy and builds the cards with DOM methods. Neither needs a framework or a package install.
Why the key stays on a server
Anything in front-end JavaScript is public: anyone can open the browser's developer tools and copy an API key from the network tab. The Big Book API terms require you to keep your key confidential and make you responsible for any misuse, so the browser never talks to Big Book API directly. The request goes through your own server instead:
browser --GET /api/similar-books?id=16384516--> your server (server.mjs)
your server --GET /16384516/similar?number=6 + x-api-key--> api.bigbookapi.com
api.bigbookapi.com --{"similar_books": [...]}--> your server --trimmed JSON--> browser The proxy also validates the book ID, so nobody can use it to send other requests on your key, and it passes on only the fields the widget shows.
What you need
- Node.js 18 or later, which has
fetchbuilt in. - A Big Book API key from the console.
- The Big Book ID of the book on the page. The example uses 16384516, Harry Potter and the Goblet of Fire in the docs. If your pages know the ISBN rather than the ID, the proxy can look the ID up first with
/search-books?isbn=, as in the Python ISBN tutorial; that costs one more request per page view.
Create a folder with three files: server.mjs, similar-books.js and index.html.
Step 1: the proxy
server.mjs uses only node:http, node:fs and the built-in fetch. It answers GET /api/similar-books?id=... and, for this demo, serves the page and the widget script.
// server.mjs: keeps the Big Book API key on the server.
// Run: BIG_BOOK_API_KEY=your-key node server.mjs
import http from 'node:http';
import { readFile } from 'node:fs/promises';
const API_KEY = process.env.BIG_BOOK_API_KEY;
const PORT = Number(process.env.PORT) || 3000;
if (!API_KEY) {
console.error('Set the BIG_BOOK_API_KEY environment variable first.');
process.exit(1);
}
// The demo page and script. In your app these come from your own server or build.
const STATIC = {
'/': ['index.html', 'text/html; charset=utf-8'],
'/similar-books.js': ['similar-books.js', 'text/javascript; charset=utf-8'],
};
function sendJson(res, status, body) {
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
// Big Book API's terms do not allow storing its data, so nothing is cached.
'Cache-Control': 'no-store',
});
res.end(JSON.stringify(body));
}
async function similarBooks(res, id) {
// Big Book IDs are numbers. Rejecting anything else keeps the upstream URL under our control.
if (!/^\d{1,12}$/.test(id)) {
return sendJson(res, 400, { error: 'id must be a numeric Big Book ID' });
}
const upstream = await fetch(`https://api.bigbookapi.com/${id}/similar?number=6`, {
headers: { 'x-api-key': API_KEY },
signal: AbortSignal.timeout(8000),
});
if (!upstream.ok) {
// 402: the free daily quota is used up. 429: over the rate limit. Other errors stay on the server.
console.error('Big Book API returned HTTP', upstream.status);
const status = upstream.status === 402 || upstream.status === 429 ? upstream.status : 502;
return sendJson(res, status, { error: status === 502 ? 'recommendations unavailable' : `HTTP ${status}` });
}
const data = await upstream.json();
// Pass on only the fields the widget shows.
const books = (data.similar_books || []).map((book) => ({
id: book.id,
title: book.title,
subtitle: book.subtitle,
image: book.image,
}));
sendJson(res, 200, { similar_books: books });
}
async function handle(req, res) {
const url = new URL(req.url, 'http://localhost');
if (req.method !== 'GET') return sendJson(res, 405, { error: 'GET only' });
if (url.pathname === '/api/similar-books') {
return similarBooks(res, url.searchParams.get('id') || '');
}
const file = STATIC[url.pathname];
if (file) {
const body = await readFile(new URL(file[0], import.meta.url));
res.writeHead(200, { 'Content-Type': file[1] });
return res.end(body);
}
sendJson(res, 404, { error: 'not found' });
}
http.createServer((req, res) => {
handle(req, res).catch((err) => {
// Network errors, timeouts and invalid JSON from upstream end up here.
console.error(err);
if (!res.headersSent) sendJson(res, 502, { error: 'could not load similar books' });
else res.end();
});
}).listen(PORT, () => console.log(`Listening on http://localhost:${PORT}/`)); What it does, from the top:
- Reads the key from the
BIG_BOOK_API_KEYenvironment variable and refuses to start without it. The key is never in the code, so it cannot end up in a repository. - Accepts only numeric IDs. Without that check, an ID such as
search-books?query=anything#would turn the URL into a call to another endpoint, and the proxy into open access to your key. - Calls
https://api.bigbookapi.com/{id}/similar?number=6with the key in thex-api-keyheader and an 8-second timeout. - Passes HTTP 402 (the free plan's daily quota is used up) and 429 (over the rate limit) through to the browser, and turns every other upstream error into 502. The details go to the server log, not to the visitor.
- Sends
Cache-Control: no-store; see caching below for why.
Step 2: the widget script
similar-books.js finds every <section class="similar-books" data-book-id="..."> on the page, fetches the proxy and fills in the list.
// similar-books.js: fills every <section class="similar-books" data-book-id="..."> on the page.
// Where a card links to. Point this at your own book pages.
function bookLink(book) {
return '/search?q=' + encodeURIComponent(book.title);
}
function renderCard(book) {
const item = document.createElement('li');
item.className = 'similar-book';
const link = document.createElement('a');
link.href = bookLink(book);
if (typeof book.image === 'string' && book.image.startsWith('https://')) {
const img = document.createElement('img');
img.src = book.image;
img.alt = book.title;
img.loading = 'lazy';
img.width = 120;
img.height = 180;
link.append(img);
}
// textContent, never innerHTML: titles are data from the API, not markup.
const title = document.createElement('span');
title.className = 'similar-book-title';
title.textContent = book.title;
link.append(title);
if (book.subtitle) {
const subtitle = document.createElement('span');
subtitle.className = 'similar-book-subtitle';
subtitle.textContent = book.subtitle;
link.append(subtitle);
}
item.append(link);
return item;
}
async function loadSimilarBooks(section) {
const list = section.querySelector('.similar-books-list');
try {
const res = await fetch('/api/similar-books?id=' + encodeURIComponent(section.dataset.bookId));
if (!res.ok) throw new Error('HTTP ' + res.status);
const data = await res.json();
const books = data.similar_books || [];
if (books.length === 0) return; // the section stays hidden
list.replaceChildren(...books.map(renderCard));
section.hidden = false;
} catch (err) {
// No shelf is better than a broken one.
console.warn('Similar books not loaded:', err);
}
}
document.querySelectorAll('.similar-books[data-book-id]').forEach(loadSimilarBooks); Some choices worth keeping when you adapt it:
- No
innerHTMLwith API data. Titles go in withtextContentand attributes are set as properties, so a title that contains<or a quote is shown as text and cannot inject markup. - Only
https://image URLs are used. A book without a cover gets a text-only card. loading="lazy"pluswidthandheight: covers below the fold load when needed, and the browser reserves their space, so the page does not jump when they arrive.- The section stays hidden until there are books to show. On an error or an empty result the page simply has no shelf.
bookLink()decides where a card points. The example links to a search on your own site; change it to match your routes.
Step 3: the page and styles
index.html is a minimal book page with the widget's markup and a compact grid layout. In your site, copy the <section>, the styles and the script tag into your book template.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Similar books widget</title>
<style>
.similar-books-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 16px;
list-style: none;
margin: 0;
padding: 0;
}
.similar-book a { display: block; color: inherit; text-decoration: none; }
.similar-book img {
display: block;
width: 100%;
height: auto;
aspect-ratio: 2 / 3;
object-fit: cover;
border-radius: 4px;
background: #eee;
}
.similar-book-title { display: block; margin-top: 6px; font-weight: 600; font-size: 14px; }
.similar-book-subtitle { display: block; font-size: 13px; color: #555; }
</style>
</head>
<body>
<h1>Harry Potter and the Goblet of Fire</h1>
<section class="similar-books" data-book-id="16384516" hidden>
<h2>Similar books</h2>
<ul class="similar-books-list"></ul>
</section>
<script src="/similar-books.js" defer></script>
</body>
</html> Run it
BIG_BOOK_API_KEY="your-api-key" node server.mjs
# Listening on http://localhost:3000/ Open http://localhost:3000/: the page shows a grid of six similar books under the title. To check the proxy on its own, request http://localhost:3000/api/similar-books?id=16384516; a non-numeric ID returns 400. On Windows PowerShell, set the key with $env:BIG_BOOK_API_KEY = "your-api-key" and then run node server.mjs.
To show more or fewer books, change number=6 in the proxy; the endpoint returns 1 to 100.
Caching, quotas and the terms
Adding a cache to the proxy looks like an easy way to save requests, but the terms do not allow storing Big Book API data. Caching user-requested data for up to one hour is allowed only with prior written permission from Big Book API, and the data must be refreshed after that hour. That is why the proxy sends Cache-Control: no-store and keeps nothing in memory. If you want a short cache, ask for permission first.
Without a cache, every page view costs one request (quotas):
- The free plan's 50 requests a day cover testing and small non-commercial sites, and it requires a backlink to bigbookapi.com. When the quota is used up the proxy gets HTTP 402 and the shelf stays hidden until the reset at midnight UTC.
- Commercial sites need a paid plan: 500, 5,000 or 50,000 requests a day for $6, $29 or $99 a month, with extra requests billed (pricing).
- Rate limits range from 1 request per second on the free plan to 20 on the largest. A traffic spike above yours produces 429s, and the affected visitors see no shelf rather than an error.
Frequently asked questions
Can I call Big Book API directly from the browser?
Not safely. Your API key would be visible to every visitor, and the terms require you to keep it confidential. Put a small server in between, as in this tutorial.
Can I cache the similar books to save requests?
Only with written permission, and then for at most one hour. The terms do not allow storing Big Book API data otherwise.
How many similar books can I get per request?
Between 1 and 100, set with the number parameter of /{id}/similar. Each call counts as one request, whatever the number.
Does this work with Express, Next.js or a serverless function?
Yes. The proxy logic is a few lines: validate the ID, call the API with the key from an environment variable, return the trimmed JSON. Any backend that can keep a secret can run it.
What happens when the daily quota runs out?
On the free plan, the API answers with HTTP 402 until midnight UTC, and the widget stays hidden. Paid plans bill extra requests instead.