Multi-account authentication

Multi-account authentication integration for external platforms.

Running this example

To run this example locally:

  1. 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.

  2. 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.

  3. Clone the starter kit:

    git clone https://github.com/canva-sdks/canva-apps-sdk-starter-kit.git
    cd canva-apps-sdk-starter-kit
    SHELL
  4. Install dependencies:

    npm install
    SHELL
  5. Run the example:

    npm run start multi_account_authentication
    SHELL
  6. 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 Portal
const 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 active
setProfile(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 client
const tokenResponse = await account.getAccessToken({ scope });
if (!tokenResponse) {
throw new Error("Failed to get access token");
}
// Fetch profile from your backend using the account access token
const 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}>
<Box
justifyContent="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>
<OauthAccountSwitcher
oauth={oauth}
scope={scope}
authorizationQueryParams={{
access_type: "offline",
prompt: "login",
}}
signInLabel="Sign in"
triggerLabel="Switch Account"
appName="Multi-account demo"
onAccountSwitch={handleAccountSwitch}
/>
{selectedAccount ? (
<>
<Box
padding="2u"
border="standard"
borderRadius="standard"
background="neutral"
>
<Rows spacing="2u">
<Title size="small">Selected Account</Title>
<Columns spacing="2u" alignY="center">
<Column width="content">
<Avatar
name={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">
<Button
variant="primary"
onClick={() => fetchProfile(selectedAccount)}
disabled={loading}
>
{loading ? "Fetching..." : "Fetch Profile"}
</Button>
</Column>
</Columns>
</Rows>
</Box>
{(profile || profileError || loading) && (
<Box
padding="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 && (
<Box
padding="2u"
borderRadius="standard"
border="standard"
>
<Text>Error: {profileError}</Text>
</Box>
)}
{profile && (
<Box
padding="2u"
background="neutral"
borderRadius="standard"
>
<Text size="small">
<pre
style={{ 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 authentication
Demonstrates 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 started
Before 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:
```sh
npm start multi_account_authentication
```
MARKDOWN

API reference

Need help?