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");const token = await auth.getCanvaUserToken();const 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-consoleconsole.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
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() {// TODO: 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();/*** TODO: 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());const jwtMiddleware = createJwtMiddleware(APP_ID);router.use(jwtMiddleware);/** TODO: Define your backend routes after initializing the jwt middleware.*/router.get("/custom-route", async (req, res) => {// eslint-disable-next-line no-consoleconsole.log("request", req.canva);res.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
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();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 for example purposes only. Production apps should not disable linting rules without proper justification- Error handling for network requests is simplified for demonstration. Production apps must implement comprehensive error handling with retry logic and user feedback- Loading states and progress indicators are not implemented. Production apps should provide visual feedback during API calls- Token management and security is simplified for demonstration. Production apps must implement secure token storage 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)