SDK for Node.js
Express helpers
Three small helpers that save you writing the same code in every app. They work with Express 4 and 5.
errorHandler(): clean error answers
Add it once, after your routes. When an SDK call fails inside a route, your user gets a short JSON answer instead of a crash.
const { errorHandler } = require("@secure-cloud/sdk");
// ...your routes...
app.use(errorHandler());What your users see:
- Their own mistakes keep their status and message, for example
404for a missing file,401for a wrong password or409for a taken email. - Problems with your setup (a wrong or revoked API key, the gateway unreachable) become a plain
500. The details are written to your server's log, never sent to the browser. - Other errors (not from the SDK) go on to Express's own error handling, as usual.
{ "error": { "code": "NOT_FOUND", "message": "File not found" } }requireUser(): signed in users only
const users = cloud.userPool(process.env.SECURE_CLOUD_POOL_ID);
app.get("/orders", users.requireUser({ cookie: "access_token" }), async (req, res) => {
res.json(await ordersFor(req.user.id));
});It reads the token from the cookie you name (or the Authorization header), checks it, and puts the user on req.user: id, email, attributes and expiresAt. Without a valid token the answer is a 401 and your route never runs.
files.send(): a download in one line
app.get("/files/:id", users.requireUser({ cookie: "access_token" }), async (req, res) => {
await cloud.files.send(res, req.params.id);
});It streams the file with its original name. Files are always sent as downloads, never shown inside the page, so a stored file can't run as part of your site.
A complete example
const express = require("express");
const cookieParser = require("cookie-parser");
const multer = require("multer");
const { SecureCloud, errorHandler } = require("@secure-cloud/sdk");
const app = express();
app.use(express.json());
app.use(cookieParser());
const cloud = new SecureCloud();
const users = cloud.userPool(process.env.SECURE_CLOUD_POOL_ID);
const upload = multer({ limits: { fileSize: 20 * 1024 * 1024 } });
const signedIn = users.requireUser({ cookie: "access_token" });
app.post("/sign-in", async (req, res) => {
const session = await users.signIn(req.body);
res.cookie("access_token", session.accessToken, { httpOnly: true, sameSite: "lax" });
res.cookie("refresh_token", session.refreshToken, { httpOnly: true, sameSite: "lax" });
res.json({ email: session.user.email });
});
app.post("/photos", signedIn, upload.single("photo"), async (req, res) => {
res.status(201).json(await cloud.files.upload(req.file));
});
app.post("/checkout", signedIn, async (req, res) => {
const charge = await cloud.connections.call("payments", "POST /charges", {
amount: req.body.amount,
currency: "sgd",
description: `Order for ${req.user.email}`,
});
res.status(charge.ok ? 201 : 402).json(charge.data);
});
app.use(errorHandler());
app.listen(3000);