Examples
App elements
Assets and media
Fundamentals
Intents
Design interaction
Drag and drop
Design elements
Localization
Content replacement
Fetch
Secure communication between apps and servers using the browser's Fetch API.
Running this example
To run this example locally:
-
If you haven't already, create a new app in the Developer Portal(opens in a new tab or window). For more information, refer to our Quickstart guide.
-
In your app's configuration on the Developer Portal(opens in a new tab or window), ensure the "Development URL" is set to
http://localhost:8080
. -
Clone the starter kit:
git clone https://github.com/canva-sdks/canva-apps-sdk-starter-kit.gitcd canva-apps-sdk-starter-kitSHELL -
Install dependencies:
npm installSHELL -
Run the example:
npm run start fetchSHELL -
Click the Preview URL link shown in the terminal to open the example in the Canva editor.
Example app source code
// For usage information, see the README.md file.import {Button,FormField,MultilineInput,Rows,Text,Title,} from "@canva/app-ui-kit";import { auth } from "@canva/user";import { useState } from "react";import * as styles from "styles/components.css";const BACKEND_URL = `${BACKEND_HOST}/custom-route`;type State = "idle" | "loading" | "success" | "error";export const App = () => {const [state, setState] = useState<State>("idle");const [responseBody, setResponseBody] = useState<unknown | undefined>(undefined,);const sendGetRequest = async () => {try {setState("loading");// Get the current user's authentication token from Canva// This token allows the backend to verify the user's identity and permissionsconst token = await auth.getCanvaUserToken();// Make authenticated request to custom backend// The Authorization header contains the JWT token for verificationconst res = await fetch(BACKEND_URL, {headers: {Authorization: `Bearer ${token}`,},});const body = await res.json();setResponseBody(body);setState("success");} catch (error) {setState("error");/* eslint-disable-next-line no-console */console.error(error);}};return (<div className={styles.scrollContainer}><Rows spacing="3u"><Text>This example demonstrates how apps can securely communicate with theirservers via the browser's Fetch API.</Text>{/* Idle and loading state */}{state !== "error" && (<><Buttonvariant="primary"onClick={sendGetRequest}loading={state === "loading"}stretch>Send GET request</Button>{state === "success" && responseBody && (<FormFieldlabel="Response"value={JSON.stringify(responseBody, null, 2)}control={(props) => (<MultilineInput {...props} maxRows={5} autoGrow readOnly />)}/>)}</>)}{/* Error state */}{state === "error" && (<Rows spacing="3u"><Rows spacing="1u"><Title size="small">Something went wrong</Title><Text>To see the error, check the JavaScript Console.</Text></Rows><Buttonvariant="secondary"onClick={() => {setState("idle");}}stretch>Reset</Button></Rows>)}</Rows></div>);};
TYPESCRIPT
// For usage information, see the README.md file.import "dotenv/config";import * as express from "express";import * as cors from "cors";import { createBaseServer } from "../../../../utils/backend/base_backend/create";import { createJwtMiddleware } from "../../../../utils/backend/jwt_middleware";async function main() {// Set the CANVA_APP_ID environment variable in the project's .env fileconst APP_ID = process.env.CANVA_APP_ID;if (!APP_ID) {throw new Error(`The CANVA_APP_ID environment variable is undefined. Set the variable in the project's .env file.`,);}const router = express.Router();/*** IMPORTANT: You must configure your CORS Policy** Cross-Origin Resource Sharing* ([CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS)) is an* [HTTP](https://developer.mozilla.org/en-US/docs/Glossary/HTTP)-header based* mechanism that allows a server to indicate any* [origins](https://developer.mozilla.org/en-US/docs/Glossary/Origin)* (domain, scheme, or port) other than its own from which a browser should* permit loading resources.** A basic CORS configuration would include the origin of your app in the* following example:* const corsOptions = {* origin: 'https://app-abcdefg.canva-apps.com',* optionsSuccessStatus: 200* }** The origin of your app is https://app-${APP_ID}.canva-apps.com, and note* that the APP_ID should to be converted to lowercase.** https://www.npmjs.com/package/cors#configuring-cors** You may need to include multiple permissible origins, or dynamic origins* based on the environment in which the server is running. Further* information can be found* [here](https://www.npmjs.com/package/cors#configuring-cors-w-dynamic-origin).*/router.use(cors());// Initialize JWT middleware to verify Canva user tokens// This middleware validates tokens sent from the frontend and extracts user informationconst jwtMiddleware = createJwtMiddleware(APP_ID);router.use(jwtMiddleware);// IMPORTANT: You must define your own backend routes after initializing the jwt middleware// This ensures all routes have access to verified user information via req.canvarouter.get("/custom-route", async (req, res) => {// Log the authenticated user information (extracted from JWT token)/* eslint-disable-next-line no-console */console.log("request", req.canva);// Return user context information from the verified JWT token// This demonstrates how to access app, user, and brand informationres.status(200).send({appId: req.canva.appId,userId: req.canva.userId,brandId: req.canva.brandId,});});const server = createBaseServer(router);server.start(process.env.CANVA_BACKEND_PORT);}main();
TYPESCRIPT
// For usage information, see the README.md file.import { AppUiProvider } from "@canva/app-ui-kit";import { createRoot } from "react-dom/client";import { App } from "./app";import "@canva/app-ui-kit/styles.css";const root = createRoot(document.getElementById("root") as Element);function render() {root.render(<AppUiProvider><App /></AppUiProvider>,);}render();// Hot Module Replacement for development (automatically reloads the app when changes are made)if (module.hot) {module.hot.accept("./app", render);}
TYPESCRIPT
# Fetch API integrationDemonstrates how to make authenticated HTTP requests to external backends using user tokens. Shows proper authentication patterns, error handling, and data retrieval from custom APIs.For API reference docs and instructions on running this example, see: https://www.canva.dev/docs/apps/examples/fetch/.Related examples: See design_interaction/design_token for design-specific API access, or fundamentals/authentication for user authentication patterns.NOTE: This example differs from what is expected for public apps to pass a Canva review:- Console.log statements are used for debugging purposes but should be replaced with proper error handling and logging in production apps- ESLint rule `no-console` is disabled in both frontend and backend code for demonstration purposes. This allows console logging for educational clarity but production apps should use structured logging solutions- Error handling for network requests is simplified for demonstration. Production apps must implement comprehensive error handling with retry logic and user feedback- CORS configuration uses `cors()` without restrictions for development ease. Production apps must configure specific allowed origins- Loading states and progress indicators are basic. Production apps should provide comprehensive visual feedback during API calls- Token management is simplified for demonstration. Production apps must implement secure token storage, validation, and rotation- Internationalization is not implemented. Production apps must support multiple languages using the `@canva/app-i18n-kit` package to pass Canva review requirements
MARKDOWN
API reference
Need help?
- Join our Community Forum(opens in a new tab or window)
- Report issues with this example on GitHub(opens in a new tab or window)