Skip to main content

Call Your Own Backend

Your app gets its data from your own backend. The iframe sends the provider's access token to your backend, and your backend calls the provider's API with it. This page explains how to call the backend from the app, how to build the backend, and how to keep tokens safe.


Step 1: Call the backend from the app​

useBackend() (src/api/useBackend.ts) returns a function that sends a request to your backend:

import { useBackend } from '@/api/useBackend';

const backend = useBackend();
const items = await backend<Item[]>('/api/items');

The function:

  • Calls ${BACKEND_HOST}${path}.
  • Accepts a standard RequestInit as its second argument, so you can set method, body, extra headers, or an abort signal.
  • Sets Authorization: Bearer <accessToken> with the latest token from useHootsuite().
  • If there is no token yet, throws an UnauthorizedError without sending the request.
  • On 401, asks the host for a renewed token with requestAccessToken(). If the host returns a different token, it repeats the request once with it.
  • If the token cannot be renewed (the host reports an error, does not answer within 8 seconds, or returns the same token) or the repeated request also gets a 401, calls requireReconnect() and throws an UnauthorizedError. needsReconnect becomes true and isAuthenticated becomes false.
  • On any other non-2xx status, throws Error('Backend request failed with status <status>').
  • Otherwise, returns the parsed JSON body.

useBackend() never opens the consent popup. When the user has to reconnect, ProtectedRoute sends them to the Authorize page, which shows a Reconnect button that calls requestAuthorization(). After the user reconnects, the template's Authorize page goes to #/home.

The returned function keeps the same identity when the token changes and always sends the latest token, so you can keep it in a long-lived callback or effect. A repeated request reuses the same init, so do not pass a body that can be read only once, such as a ReadableStream.

Call it only from pages wrapped in ProtectedRoute, or after checking isAuthenticated, so that a token is available.

Call your backend without useBackend()​

If you reach your backend another way, for example with a client library or a streaming connection, follow the same steps:

  1. Send the token from useHootsuite() as Authorization: Bearer <accessToken>.
  2. On 401, call requestAccessToken(). If it resolves with a token different from the one that failed, retry once with it.
  3. Otherwise, call requireReconnect(rejectedToken) and let the user reconnect from a button.

Example: load data with loading, empty, and error states​

This example, for an app that shows Todoist tasks, loads the tasks once when the page mounts and cancels the request if the page unmounts:

import React, { useEffect, useState } from 'react';
import { Box } from 'hootsuite-bento';
import { UnauthorizedError, useBackend } from '@/api/useBackend';

type Task = { id: string; content: string };

export function Tasks(): React.ReactElement {
const backend = useBackend();
const [tasks, setTasks] = useState<Task[]>([]);
const [loadState, setLoadState] = useState<'loading' | 'ready' | 'error'>('loading');

useEffect(() => {
const controller = new AbortController();
setLoadState('loading');

backend<Task[]>('/api/items', { signal: controller.signal })
.then((result) => {
setTasks(result);
setLoadState('ready');
})
.catch((error: unknown) => {
if (error instanceof DOMException && error.name === 'AbortError') {
return;
}
if (error instanceof UnauthorizedError) {
// The template shows the Reconnect screen.
return;
}
setLoadState('error');
});

return () => controller.abort();
}, [backend]);

if (loadState === 'loading') {
return <Box attributes={{ role: 'status', 'aria-live': 'polite' }}>Loading tasks…</Box>;
}
if (loadState === 'error') {
return <Box attributes={{ role: 'alert' }}>Tasks could not be loaded. Close and reopen the app to try again.</Box>;
}
if (tasks.length === 0) {
return <Box attributes={{ role: 'status', 'aria-live': 'polite' }}>No tasks to show.</Box>;
}
return (
<Box as="ul">
{tasks.map((task) => (
<Box as="li" key={task.id}>
{task.content}
</Box>
))}
</Box>
);
}

If the token expired while the app was open, useBackend() renews it and the request succeeds without the user noticing. If renewal fails, the request rejects with UnauthorizedError, and ProtectedRoute replaces the page with the Reconnect screen. After the user reconnects, the page mounts again and loads its data. A renewed token alone does not run the effect again, because backend keeps the same identity.


Step 2: Build the backend​

The template includes an example Express backend in server/. Use it as a starting point or replace it with any stack.

EndpointDescription
GET /healthHealth check.
GET /api/itemsExample route. Calls ${EXTERNAL_API_BASE_URL}/items with the token the iframe sent, and returns 401 if the token is missing or the provider rejects it.

Read the Bearer token​

Protect your routes with requireBearer (server/middleware/auth.ts). It returns 401 if the Authorization: Bearer <token> header is missing, and otherwise exposes the token as req.accessToken:

import { Router, Response, NextFunction } from 'express';
import { requireBearer, AuthenticatedRequest } from '../middleware/auth';

export const router = Router();

router.get(
'/items',
requireBearer,
async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const upstream = await fetch(`${process.env.EXTERNAL_API_BASE_URL}/items`, {
headers: {
Authorization: `Bearer ${req.accessToken}`,
Accept: 'application/json',
},
});

if (upstream.status === 401) {
res.status(401).json({ error: 'Unauthorized', message: 'The provider rejected the access token' });
return;
}

res.status(upstream.status).json(await upstream.json());
} catch (error) {
next(error);
}
}
);

requireBearer does not validate the token. Provider tokens are usually opaque, so the provider's API is what rejects invalid or expired tokens.

Return 401 when the provider rejects the token​

Always pass a provider 401 back to the iframe as 401. Do not convert it into a 500 or a 200 with an empty list: the 401 is what makes the app ask Hootsuite for a renewed token and, if that fails, offer Reconnect. This covers a token that expired while the app was open and users who revoked your app in the provider's settings. Hootsuite renews expired tokens when the app starts, so a 401 is not expected on a freshly opened app unless renewal failed (see Token renewal).

Adapt the route to your provider​

Map the provider's response into the shape your UI needs. For example, Todoist's GET /tasks endpoint is paginated with a cursor, so this backend route follows every page and returns one flat array:

const tasks: unknown[] = [];
let cursor: string | null = null;

do {
const pageUrl = new URL(`${baseUrl}/tasks`);
pageUrl.searchParams.set('limit', '200');
if (cursor) {
pageUrl.searchParams.set('cursor', cursor);
}

const upstream = await fetch(pageUrl, {
headers: { Authorization: `Bearer ${req.accessToken}`, Accept: 'application/json' },
});
if (upstream.status === 401) {
res.status(401).json({ error: 'Unauthorized', message: 'Todoist rejected the access token' });
return;
}

const body = await upstream.json();
if (!upstream.ok) {
res.status(upstream.status).json(body);
return;
}

tasks.push(...body.results);
cursor = body.next_cursor || null;
} while (cursor);

res.json(tasks);

In production code, also validate the provider's response shape and stop if the provider repeats a cursor.


Step 3: Configure CORS​

The iframe calls your backend from your app's origin, so the backend must allow that origin with CORS. The example backend allows:

OriginWhen
https://<HOOTSUITE_APP_ID>.hootsuite-apps.comAlways. This is the origin of the hosted bundle.
https://localhost:<FRONTEND_PORT>Only when NODE_ENV is not production. This is the origin of the dev server.

Your hosted app runs on the first origin in the table, so that one must always be allowed. To use your own list, set the optional ALLOWED_ORIGINS variable in .env, with the origins separated by commas. For production, list only the hosted origin:

ALLOWED_ORIGINS=https://<YOUR_APP_ID>.hootsuite-apps.com

For local development, also list the dev server's origin (use your FRONTEND_PORT):

ALLOWED_ORIGINS=https://<YOUR_APP_ID>.hootsuite-apps.com,https://localhost:8080

When ALLOWED_ORIGINS is set, it replaces the table above exactly: nothing is added, and NODE_ENV does not change it. Include the hosted origin yourself, and leave localhost out of your production list. Leave the variable empty to use the table. A trailing slash or a path is ignored (https://example.com/some/path is read as https://example.com), and entries that are not http or https origins are ignored.

When the backend starts, it prints Allowed origins: ... and warns about ignored entries or a localhost origin in production. Check that line first when the browser reports a CORS error. The backend reads .env once, so after you change it, stop npm start and run it again.

It allows the methods GET, POST, PUT, DELETE, and OPTIONS, and the headers Content-Type and Authorization. Requests from other origins receive no CORS headers, so the browser blocks them. Requests without an Origin header, such as curl, are allowed.

If you write your own backend, apply the same rules. Do not use Access-Control-Allow-Origin: *.

You can check the preflight from a terminal:

curl -i -X OPTIONS https://<YOUR_BACKEND_HOST>/api/items \
-H "Origin: https://<YOUR_APP_ID>.hootsuite-apps.com" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: Authorization"

The response should include Access-Control-Allow-Origin: https://<YOUR_APP_ID>.hootsuite-apps.com.


Step 4: Deploy on public HTTPS​

Once the bundle is hosted by Hootsuite, your backend must be reachable on a public HTTPS URL:

  1. Deploy the backend on a stable domain, for example https://api.example.com.
  2. Set NODE_ENV=production on the server, so the example backend does not add the localhost origin by default and hides error details. If you set ALLOWED_ORIGINS, list only https://<YOUR_APP_ID>.hootsuite-apps.com there: NODE_ENV does not remove entries from it.
  3. Set BACKEND_HOST=https://api.example.com in .env, then rebuild and upload the bundle.

BACKEND_HOST is written into app.js at build time. Every time the backend URL changes, you need a new build and upload. Keep one build per environment, and avoid URLs that change often, such as temporary tunnels. A production build prints BACKEND_HOST should not be localhost for production builds! if you forget to change it.


Token handling rules​

The provider's access token gives access to the user's data in the provider. Treat it as a secret:

  • Do not store tokens. Use the token sent with each request, and do not save it in a database, cache, or file. Hootsuite keeps the refresh token and renews the access token when the app asks for it, so your backend always receives a current token.
  • Do not log tokens. Do not log the Authorization header, full request headers, or provider responses that echo the token. The example backend logs only the method and path.
  • Do not send tokens anywhere except your provider. Forward the token only to the provider API it belongs to.
  • Do not put tokens in URLs. Keep them in the Authorization header so they do not appear in server or proxy logs.
  • Do not persist tokens in the browser. Do not write the token to localStorage, sessionStorage, or cookies. useHootsuite() keeps it in memory.
  • Keep secrets out of the bundle. Everything in app.js is public. Never put a client secret or API key in .env values that webpack injects into the frontend.

Next step​

Surface context reference.