Examples
App elements
Assets and media
Fundamentals
Intents
Design interaction
Drag and drop
Design elements
Localization
Content replacement
Authentication
Third-party authentication integration for external platforms.
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 authenticationSHELL -
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,LoadingIndicator,Rows,Title,Text,Box,MultilineInput,FormField,} from "@canva/app-ui-kit";import { useMemo, useState, useEffect, useCallback } from "react";import type { AccessTokenResponse } from "@canva/user";import { auth } from "@canva/user";import * as styles from "styles/components.css";const scope = new Set(["openid"]);const BACKEND_URL = `${BACKEND_HOST}/custom-route`;export function App() {// initialize the OAuth clientconst oauth = useMemo(() => auth.initOauth(), []);const [accessTokenResponse, setAccessTokenResponse] = useState<AccessTokenResponse | undefined>(undefined);const [error, setError] = useState<string | null>(null);const loading = accessTokenResponse === undefined;const [responseBody, setResponseBody] = useState<unknown | undefined>(undefined,);useEffect(() => {// check if the user is already authenticatedretrieveAndSetToken();}, [oauth]);const authorize = useCallback(async () => {setAccessTokenResponse(undefined);setError(null);try {await oauth.requestAuthorization({ scope });await retrieveAndSetToken();} catch (error) {setError(error instanceof Error ? error.message : "Unknown error");}}, []);// you MUST call getAccessToken every time you need a token, as the token may expire.// Canva will handle caching and refreshing the token for you.const retrieveAndSetToken = useCallback(async (forceRefresh = false) => {try {setAccessTokenResponse(await oauth.getAccessToken({ forceRefresh, scope }),);} catch (error) {setError(error instanceof Error ? error.message : "Unknown error");}}, []);const logout = useCallback(async () => {setAccessTokenResponse(undefined);await oauth.deauthorize();setAccessTokenResponse(null);}, []);const fetchData = useCallback(async () => {const accessToken = accessTokenResponse?.token;if (!accessToken) {return;}try {const res = await fetch(BACKEND_URL, {headers: {Authorization: `Bearer ${accessToken}`,},});const data = await res.json();setResponseBody(data);} catch (error) {setError(error instanceof Error ? error.message : "Unknown error");}}, [accessTokenResponse]);const result = (<div className={styles.scrollContainer}><BoxjustifyContent="center"width="full"alignItems="center"display="flex"height="full">{error ? (<Rows spacing="2u"><Title>Authorization error</Title><Text>{error}</Text><Button variant="primary" onClick={authorize}>Try again</Button></Rows>) : loading ? (<LoadingIndicator />) : !accessTokenResponse ? (<Rows spacing="2u"><Title>Sign in required</Title><Text>This example demonstrates how apps can allow users to authorizewith the app via a third-party platform.</Text><Text>To set up please see the README.md in the/examples/fundamentals/authentication folder</Text><Text>To use "Example App", you must sign in with your "Example"account.</Text><Button variant="primary" onClick={authorize}>Sign into Example</Button></Rows>) : (<Rows spacing="2u"><Text>Logged in!</Text><Buttonvariant="primary"onClick={async () => {logout();}}>Log out</Button><Button variant="primary" onClick={fetchData}>Fetch data</Button>{responseBody ? (<FormFieldlabel="Response"value={JSON.stringify(responseBody, null, 2)}control={(props) => (<MultilineInput {...props} maxRows={5} autoGrow readOnly />)}/>) : null}</Rows>)}</Box></div>);return result;}
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
# AuthenticationDemonstrates how to implement OAuth authentication flow for accessing external services on behalf of users. Shows token management, user authorization, and authenticated API requests.For API reference docs and instructions on running this example, see: https://www.canva.dev/docs/apps/examples/authentication/.Related examples: See fundamentals/fetch for general API communication, or design_interaction/design_token for design-specific authentication patterns.NOTE: This example differs from what is expected for public apps to pass a Canva review:- Token storage and security is simplified for demonstration. Production apps must implement secure token storage and follow OAuth security best practices- Error handling for authentication failures is simplified for demonstration. Production apps must implement comprehensive error handling with clear user feedback and graceful failure modes- Token refresh mechanisms are not implemented. Production apps should implement proper token lifecycle management- Internationalization is not implemented. Production apps must support multiple languages using the `@canva/app-i18n-kit` package to pass Canva review requirements
MARKDOWN
# Setup## Getting startedBefore using this example, you'll need to [configure your provider details](https://www.canva.dev/docs/apps/authenticating-users/oauth/#prerequisite-configure-developer-portal) in the developer portal.Once this is done, simply run the example from the root of `canva-apps-sdk-starter-kit` with:```shnpm start authentication```
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)