Examples
App elements
Assets and media
Fundamentals
Intents
Design interaction
Drag and drop
Design elements
Localization
Content replacement
Multi-account authentication
Multi-account 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 multi_account_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 {Avatar,Button,Columns,Column,LoadingIndicator,Rows,Title,Text,Box,} from "@canva/app-ui-kit";import { useMemo, useState, useCallback } from "react";import { auth } from "@canva/user";import type { OauthAccount } from "@canva/user";import * as styles from "styles/components.css";import { OauthAccountSwitcher } from "@canva/app-components";// Provider name as defined in the Developer Portalconst PROVIDER = "my_provider_name" as const;const scope = new Set(["profile", "email", "openid"]);const BASE_URL = BACKEND_HOST;export function App() {const [selectedAccount, setSelectedAccount] = useState<OauthAccount | null>(null,);const [loading, setLoading] = useState(false);const [profile, setProfile] = useState<Record<string, unknown> | null>(null);const [profileError, setProfileError] = useState<string | null>(null);const oauth = useMemo(// Initialize the Canva OAuth client for user authentication() => auth.initOauth({ type: "multi_account", provider: PROVIDER }),[],);const handleAccountSwitch = useCallback((account: OauthAccount | null) => {setSelectedAccount(account);// Clear profile data when switching accounts or when no account is activesetProfile(null);setProfileError(null);}, []);const fetchProfile = useCallback(async (account: OauthAccount) => {setLoading(true);setProfileError(null);setProfile(null);try {// Get access token for the account using the correct OAuth clientconst tokenResponse = await account.getAccessToken({ scope });if (!tokenResponse) {throw new Error("Failed to get access token");}// Fetch profile from your backend using the account access tokenconst response = await fetch(`${BASE_URL}/userinfo`, {method: "GET",headers: {Authorization: `Bearer ${tokenResponse.token}`,Accept: "application/json",},});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const profileData = await response.json();setProfile(profileData);} catch (err) {setProfileError(err instanceof Error ? err.message : "Unknown error");} finally {setLoading(false);}}, []);return (<div className={styles.scrollContainer}><BoxjustifyContent="center"width="full"height="full"alignItems="center"display="flex"><Rows spacing="2u"><Title>Multi-account authentication</Title><Text>{selectedAccount? "Switch between your linked accounts or manage your connections.": "To get started, sign in using the button below."}</Text><OauthAccountSwitcheroauth={oauth}scope={scope}authorizationQueryParams={{access_type: "offline",prompt: "login",}}signInLabel="Sign in"triggerLabel="Switch Account"appName="Multi-account demo"onAccountSwitch={handleAccountSwitch}/>{selectedAccount ? (<><Boxpadding="2u"border="standard"borderRadius="standard"background="neutral"><Rows spacing="2u"><Title size="small">Selected Account</Title><Columns spacing="2u" alignY="center"><Column width="content"><Avatarname={selectedAccount.displayName}photo={selectedAccount.avatarUrl}/></Column><Column><Rows spacing="1u"><Text size="medium">{selectedAccount.displayName}</Text><Text size="small">{selectedAccount.principal}</Text></Rows></Column><Column width="content"><Buttonvariant="primary"onClick={() => fetchProfile(selectedAccount)}disabled={loading}>{loading ? "Fetching..." : "Fetch Profile"}</Button></Column></Columns></Rows></Box>{(profile || profileError || loading) && (<Boxpadding="3u"border="standard"borderRadius="standard"background="neutral"><Rows spacing="2u"><Title size="small">Profile Information</Title>{loading && (<Box display="flex" justifyContent="center"><LoadingIndicator /></Box>)}{profileError && (<Boxpadding="2u"borderRadius="standard"border="standard"><Text>Error: {profileError}</Text></Box>)}{profile && (<Boxpadding="2u"background="neutral"borderRadius="standard"><Text size="small"><prestyle={{ whiteSpace: "pre-wrap", fontSize: "12px" }}>{JSON.stringify(profile, null, 2)}</pre></Text></Box>)}</Rows></Box>)}</>) : null}</Rows></Box></div>);}
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";import { AppI18nProvider } from "@canva/app-i18n-kit";import type { DesignEditorIntent } from "@canva/intents/design";import { prepareDesignEditor } from "@canva/intents/design";async function render() {const root = createRoot(document.getElementById("root") as Element);root.render(<AppI18nProvider><AppUiProvider><App /></AppUiProvider></AppI18nProvider>,);}const designEditor: DesignEditorIntent = { render };prepareDesignEditor(designEditor);// Hot Module Replacement for development (automatically reloads the app when changes are made)if (module.hot) {module.hot.accept("./app", render);}
TYPESCRIPT
# Multi-account authenticationDemonstrates how to implement multi-account OAuth authentication, allowing users to connect and switch between multiple accounts from the same OAuth provider. Shows account management, account switching UI, token management, and authenticated API requests using the selected account.For API reference docs and instructions on running this example, see: https://www.canva.dev/docs/apps/authenticating-users/oauth-multi-account/.Related examples: See fundamentals/authentication for single-account OAuth authentication, 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- The code structure is simplified: Production apps using [intents](https://www.canva.dev/docs/apps/intents/) are recommended to call the prepareDesignEditor function from src/intents/design_editor/index.tsx
MARKDOWN
# Setup## Getting startedBefore using this example, you'll need to [add multi-account OAuth configuration to your app](https://www.canva.dev/docs/apps/authenticating-users/oauth-multi-account/#add-multi-account-oauth-to-your-app) in the developer portal.Once this is done, simply run the example from the root of `canva-apps-sdk-starter-kit` with:```shnpm start multi_account_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)