Clerk
Blog

Back

Guide


Dec 28, 2022

Back

Guide


Dec 28, 2022

Clerk and Create T3 Turbo

James Perkins

James Perkins


This guide shows you how to integrate Clerk into T3-Turbo so you can have user management for everyone.


T3-Turbo is one of the easiest ways to get both Type safety while using Next.js and Expo. The biggest missing feature is the ability to share authentication between your applications.

This guide shows you how to integrate Clerk into T3-Turbo so you can have user management for everyone.

If you don’t want to do this manually, use the starter repo. It is open source and free.

Assumptions

There are a few assumptions here when working through this guide.

  • You understand TRPC and its functionality.
  • You are familiar with Expo.
  • You have a working knowledge of Turborepo

Setup

Create your free Clerk account

You need a free Clerk account to use everything in this guide, so head to https://dashboard.clerk.com and sign up for your free account.

Create a new application in the dashboard

You will need to create a new application, name it and select Discord as a social sign-in.

If you change any setting here, you may need to update your Expo code to handle any requirements you change.

Image of application creation

Showing Only Discord

Update .env to use your keys

Under the dashboard, you will need your API keys and create a copy of the .env.example as .env

API Keys

Adding global env to Turbo


We want to have our env available in many parts of our application. You can add the following to our turbo.json .

1
"globalEnv": [
2
"DATABASE_URL",
3
"NEXT_PUBLIC_CLERK_FRONTEND_API",
4
"CLERK_API_KEY",
5
"CLERK_JWT_KEY"
6
]


Update Next.js package.json

We need to be able to access the .env when working in development, so replace the dev script with the following:

1
"with-env": "dotenv -e ../../.env --",
2
"dev": "pnpm with-env next dev",

Updating our Next.js application

First, we will work on our Next.js application, whose only change is adding Clerk, so we have powerful user authentication.

Install

1
pnpm install @clerk/nextjs --filter @acme/nextjs

Now that the Clerk package has been installed in our Next.js application, we need to wrap our application in the <ClerkProvider>, which gives us access to the authentication state throughout our application.

Open up your _app.tsx file and modify the code.

1
import "../styles/globals.css";
2
import type { AppType } from "next/app";
3
import { ClerkProvider } from "@clerk/nextjs";
4
import { trpc } from "../utils/trpc";
5
6
const MyApp: AppType = ({ Component, pageProps: { ...pageProps } }) => {
7
return (
8
<ClerkProvider {...pageProps}>
9
<Component {...pageProps} />
10
</ClerkProvider>
11
);
12
};
13
14
export default trpc.withTRPC(MyApp);

Add Middleware.ts

Clerk uses Next.js middleware to allow your application to keep track of authentication behind the scenes.

1
import { withClerkMiddleware } from "@clerk/nextjs/server";
2
import { NextResponse } from "next/server";
3
import type { NextRequest } from "next/server";
4
5
export default withClerkMiddleware((_req: NextRequest) => {
6
return NextResponse.next();
7
});
8
9
// Stop Middleware running on static files
10
export const config = {
11
matcher: [
12
/*
13
* Match request paths except for the ones starting with:
14
* - _next
15
* - static (static files)
16
* - favicon.ico (favicon file)
17
*
18
* This includes images, and requests from TRPC.
19
*/
20
"/(.*?trpc.*?|(?!static|.*\\..*|_next|favicon.ico).*)",
21
],
22
};

You will notice the matcher at the bottom, which ensures that middleware doesn’t run on every request. This will scope it to TRPC + API routes leaving your images and static files alone.

Embedding our UI components

Clerk provides highly customizable components from Sign-up to Organization management. They require zero form creation or state management, making them easy to implement. Each component will use the Next.js optional catch all route. This allows you to redirect the user inside your application using OAuth providers.

Sign in

1
import { SignIn } from "@clerk/nextjs";
2
3
const SignInPage = () => (
4
<main className="flex h-screen flex-col items-center bg-gradient-to-b from-[#2e026d] to-[#15162c] text-white">
5
<div className="flex flex-col items-center justify-center gap-4">
6
<div className="container flex flex-col items-center justify-center gap-12 px-4 py-8">
7
<h1 className="text-5xl font-extrabold tracking-tight sm:text-[5rem]">
8
Sign In
9
</h1>
10
<SignIn path="/sign-in" routing="path" signUpUrl="/sign-up" />
11
</div>
12
</div>
13
</main>
14
);
15
16
export default SignInPage;

Sign up

1
import { SignUp } from "@clerk/nextjs";
2
3
const SignUpPage = () => (
4
<main className="flex h-screen flex-col items-center bg-gradient-to-b from-[#2e026d] to-[#15162c] text-white">
5
<div className="flex flex-col items-center justify-center gap-4">
6
<div className="container flex flex-col items-center justify-center gap-12 px-4 py-8">
7
<h1 className="text-5xl font-extrabold tracking-tight sm:text-[5rem]">
8
Sign In
9
</h1>
10
<SignUp path="/sign-up" routing="path" signInUrl="/sign-in" />
11
</div>
12
</div>
13
</main>
14
);
15
16
export default SignUpPage;

Updating index.tsx

The final step for Next.js is to update our index.tsx to use Clerk. Once we update this page, users will have a way to sign in, sign out and see data from TRPC in the future.

We need to import a prebuilt component from Clerk and a hook that allow us to access the current auth state.

import { useAuth, UserButton } from "@clerk/nextjs";

What is useAuth?

The useAuth hook is a convenient way to access the current auth state. This hook provides the minimal information needed for data-loading, such as the user id and helper methods to manage the current active session.

What is UserButton?

Initially popularized by Google, users have come to expect that little photo of themselves in the top-right of the page – it’s the access point to manage their account, switch accounts, or sign out.

The <UserButton/> component renders this familiar user button UI. It renders a clickable user avatar - when clicked, the full UI opens as a popup. Here is an example

User Button Example

Updating AuthShowcase

The AuthShowCase component in the index.tsx file needs to be updated to use the useAuth() hook, allow the user to sign in, and show our UserButton if the user is signed in.

const AuthShowcase: React.FC = () => {
const { isSignedIn } = useAuth();

Now we can update our secret message from { enabled: !!session?.user } to { enabled: isSignedIn }

const AuthShowcase: React.FC = () => {
const { isSignedIn } = useAuth();
const { data: secretMessage } = trpc.auth.getSecretMessage.useQuery(
undefined,
{ enabled: isSignedIn },
);

Now the final change is to use isSignedIn in our return statement to conditionally show the secret message and UserButton component or show a sign-in link. We can do that by replacing {session?.user && ( with isSignedIn and underneath, providing the false statement using !isSignedIn this is where we can place a Link to our mounted /sign-in page.

{isSignedIn && (
<>
<p className="text-center text-2xl text-white">
{secretMessage && (
<span>
{" "}
{secretMessage} click the user button!
<br />
</span>
)}
</p>
<div className="flex items-center justify-center">
<UserButton
appearance={{
elements: {
userButtonAvatarBox: {
width: "3rem",
height: "3rem",
},
},
}}
/>
</div>
</>
)}

The UserButton component allows users to manage their accounts, including signing out or updating their profile and password or linking a new account through OAuth providers. I added some customization to make the UserButton larger.

To learn more about customization, go to our documentation where we explain how to use the appearance prop

The final step is to add a login text that pushes the user to the mounted sign-in page.

{!isSignedIn && (
<p className="text-center text-2xl text-white">
<Link href="/sign-in">Sign In</Link>
</p>
)
}

Below is the final AuthShowcase.

1
const AuthShowcase: React.FC = () => {
2
const { isSignedIn } = useAuth();
3
const { data: secretMessage } = trpc.auth.getSecretMessage.useQuery(
4
undefined,
5
{ enabled: !!isSignedIn },
6
);
7
8
return (
9
<div className="flex flex-col items-center justify-center gap-4">
10
{isSignedIn && (
11
<>
12
<p className="text-center text-2xl text-white">
13
{secretMessage && (
14
<span>
15
{" "}
16
{secretMessage} click the user button!
17
<br />
18
</span>
19
)}
20
</p>
21
<div className="flex items-center justify-center">
22
<UserButton
23
appearance={{
24
elements: {
25
userButtonAvatarBox: {
26
width: "3rem",
27
height: "3rem",
28
},
29
},
30
}}
31
/>
32
</div>
33
</>
34
)}
35
{!isSignedIn && (
36
<p className="text-center text-2xl text-white">
37
<Link href="/sign-in">Sign In</Link>
38
</p>
39
)}
40
</div>
41
);
42
};

Now that the Next.js work is done, we should update our TRPC API to use Clerk instead of NextAuth, so we can test this work and get ready to update Expo.

Updating API package to use Clerk

Currently, the API package has TRPC context, and middleware uses Auth.js (previously NextAuth). We can replace this with Clerk so we can use it both with Expo and Next.js.

You can delete the Auth package in the packages folder completely and update the Prisma schema to remove the user data. None of this is needed to use Clerk makes sure you remove any references if you do this

Updating TRPC context

The context is found at packages/api/src/context.ts. In this package, we will add the ability to detect the user being signed in and retrieve the full User object. First, we must remove the auth package import and add getAuth , clerkClient, SignedInAuthObject and SignedOutAuthObject as a type.

1
- import { getServerSession, type Session } from "@acme/auth";
2
+ import { getAuth } from "@clerk/nextjs/server";
3
+ import type { SignedInAuthObject,SignedOutAuthObject,} from "@clerk/nextjs/api";

What is getAuth ?

The getAuth() helper retrieves the authentication state and can be used anywhere within a next.js server. It provides information needed for data-loading, such as the user id and can be used to protect your API routes.

Updating createContext function

For the createContext function, we want to pass around the user object anywhere in our application. For this, we can create an async function called getUser that retrieves the userId and subsequently retrieves the user data.

export const createContext = async (opts: CreateNextContextOptions) => {
return await createContextInner({ auth: getAuth(opts.req) });
};

Now we can retrieve a user, and if not, we will return null we can pass this to our createContextInner in case you need it for testing without a request object.

type AuthContextProps = {
auth: SignedInAuthObject | SignedOutAuthObject;
};
/** Use this helper for:
* - testing, where we dont have to Mock Next.js' req/res
* - trpc's `createSSGHelpers` where we don't have req/res
* @see https://beta.create.t3.gg/en/usage/trpc#-servertrpccontextts
*/
export const createContextInner = async ({ auth }: AuthContextProps) => {
return {
auth,
prisma,
};
};

Updating TRPC middleware

The TRPC middleware found in /packages/api/src/trpc.ts needs a small update to the isAuthed function. The if statement becomes !ctx.auth.userId, and the return becomes auth: ctx.auth

1
import { initTRPC, TRPCError } from "@trpc/server";
2
import { type Context } from "./context";
3
import superjson from "superjson";
4
5
const t = initTRPC.context<Context>().create({
6
transformer: superjson,
7
errorFormatter({ shape }) {
8
return shape;
9
},
10
});
11
12
const isAuthed = t.middleware(({ next, ctx }) => {
13
if (!ctx.auth.userId) {
14
throw new TRPCError({ code: "UNAUTHORIZED", message: "Not authenticated" });
15
}
16
return next({
17
ctx: {
18
auth: ctx.auth,
19
},
20
});
21
});
22
23
export const router = t.router;
24
export const publicProcedure = t.procedure;
25
export const protectedProcedure = t.procedure.use(isAuthed);

Our Next.js application can be tested with TRPC, including the secret message that uses protected routes. Give it a test.

Updating our Expo application

The Expo application currently doesn’t support authentication; the good news is Clerk supports Expo with our @clerk/expo package.

Install @clerk/expo package and secure-store

pnpm install @clerk/clerk-expo expo-secure-store --filter @acme/expo

Create a Token Cache

We need a token cache here, which is why we installed expo-secure-store that allows you to store key pair values on the device. Create a new file under /src/utils/ named cache.ts and paste in the following code:

1
import * as SecureStore from "expo-secure-store";
2
import { Platform } from "react-native";
3
4
export async function saveToken(key: string, value: string) {
5
// console.log("Save token", key, value);
6
await SecureStore.setItemAsync(key, value);
7
}
8
9
export async function getToken(key: string) {
10
const value = await SecureStore.getItemAsync(key);
11
return value;
12
}
13
14
// SecureStore is not supported on the web
15
// https://github.com/expo/expo/issues/7744#issuecomment-611093485
16
export const tokenCache =
17
Platform.OS !== "web"
18
? {
19
getToken,
20
saveToken,
21
}
22
: undefined;

I won’t explain this code above as it’s an expo-specific package, but this allows us to store the JWT securely and not in memory.

Add <ClerkProvider>

Similar to our Next.js application, we need to wrap up our _app.tsx in the <ClerkProvider> to allow access to auth state anywhere in the application. What is different here is we need use our newly created TokenCache, and we need to provide the Clerk frontend API directly to the <ClerkProvider />

1
import { StatusBar } from "expo-status-bar";
2
import React from "react";
3
import { SafeAreaProvider } from "react-native-safe-area-context";
4
import { TRPCProvider } from "./utils/trpc";
5
6
import { HomeScreen } from "./screens/home";
7
import { ClerkProvider } from "@clerk/clerk-expo";
8
import { tokenCache } from "./utils/cache";
9
10
// Find this in your Dashboard.
11
const clerk_frontend_api = "FRONT_END_API";
12
13
export const App = () => {
14
return (
15
<ClerkProvider frontendApi={clerk_frontend_api} tokenCache={tokenCache}>
16
<TRPCProvider>
17
<SafeAreaProvider>
18
<HomeScreen />
19
<StatusBar />
20
</SafeAreaProvider>
21
</TRPCProvider>
22
</ClerkProvider>
23
)
24
}

Protecting pages

Our Expo package provides an easy way to gate content using SignedIn and SignedOut, which will gate the content depending on the user's current state.

1
import { StatusBar } from "expo-status-bar";
2
import React from "react";
3
import { SafeAreaProvider } from "react-native-safe-area-context";
4
import { TRPCProvider } from "./utils/trpc";
5
6
import { HomeScreen } from "./screens/home";
7
import { ClerkProvider, SignedIn, SignedOut } from "@clerk/clerk-expo";
8
import { tokenCache } from "./utils/cache";
9
10
// Find this in your Dashboard.
11
const clerk_frontend_api = "FRONT_END_API";
12
13
export const App = () => {
14
return (
15
<ClerkProvider frontendApi={clerk_frontend_api} tokenCache={tokenCache}>
16
<SignedIn>
17
<TRPCProvider>
18
<SafeAreaProvider>
19
<HomeScreen />
20
<StatusBar />
21
</SafeAreaProvider>
22
</TRPCProvider>
23
</SignedIn>
24
<SignedOut>
25
26
</SignedOut>
27
</ClerkProvider>
28
);
29
};

Implementing a way to sign in.

With Clerk Expo, you must implement your pages to sign in or sign up as a user. We will use Discord, but you can use any social or standard sign-in you want. First, we need to install expo-auth-session to handle sessions.

pnpm install expo-auth-sessions --filter @acme/expo

Creating a Sign In component

Create a folder called components and then create a file called SignInWithOAuth.tsx. This will be our component that you can easily extend to use more providers or swap out Discord for something else.

import { useSignIn } from "@clerk/clerk-expo";
import React from "react";
import { Button, View } from "react-native";
import * as AuthSession from "expo-auth-session";
const SignInWithOAuth = () => {
const { isLoaded, signIn, setSession } = useSignIn();
}

Here we are using another helper, which allows you to sign in as a user and set the session after the fact. We need to make sure Clerk is fully loaded before we attempt a sign in so we can use the isLoaded as part of the useSignIn helper.

import { useSignIn } from "@clerk/clerk-expo";
import React from "react";
import { Button, View } from "react-native";
import * as AuthSession from "expo-auth-session";
const SignInWithOAuth = () => {
const { isLoaded, signIn, setSession } = useSignIn();
if (!isLoaded) return null;
}

Now we need to create our function that will run when a user taps the button to sign in:

import { useSignIn } from "@clerk/clerk-expo";
import React from "react";
import { Button, View } from "react-native";
import * as AuthSession from "expo-auth-session";
const SignInWithOAuth = () => {
const { isLoaded, signIn, setSession } = useSignIn();
if (!isLoaded) return null;
const handleSignInWithDiscordPress = async () => {
try {

Next we need to tell where to redirect to after a successful or unsuccessful login attempt via Discord,expo-auth-session provides a helper to make a redirect, which is called makeRedirectUri, and set it to /oauth-native-callback

import { useSignIn } from "@clerk/clerk-expo";
import React from "react";
import { Button, View } from "react-native";
import * as AuthSession from "expo-auth-session";
const SignInWithOAuth = () => {
const { isLoaded, signIn, setSession } = useSignIn();
if (!isLoaded) return null;
const handleSignInWithDiscordPress = async () => {
try {
const redirectUrl = AuthSession.makeRedirectUri({
path: "/oauth-native-callback",
});

At this point, we can start our sign in attempt using signIn.create passing in our strategy, which is oauth_discord, and our newly created redirectUrl

import { useSignIn } from "@clerk/clerk-expo";
import React from "react";
import { Button, View } from "react-native";
import * as AuthSession from "expo-auth-session";
const SignInWithOAuth = () => {
const { isLoaded, signIn, setSession } = useSignIn();
if (!isLoaded) return null;
const handleSignInWithDiscordPress = async () => {
try {
const redirectUrl = AuthSession.makeRedirectUri({
path: "/oauth-native-callback",
});
await signIn.create({
strategy: "oauth_discord",
redirectUrl,
});

The SignIn object holds all the state of the current sign in and provides helper methods to navigate and complete the sign in process. You can read about this in our documentation, as you may want to use the different sign in methods in the future.

The next part of the sign in is to retrieve the external redirect URL and use AuthSession. This will give us the ability to know if the OAuth was successful or not.

import { useSignIn } from "@clerk/clerk-expo";
import React from "react";
import { Button, View } from "react-native";
import * as AuthSession from "expo-auth-session";
const SignInWithOAuth = () => {
const { isLoaded, signIn, setSession } = useSignIn();
if (!isLoaded) return null;
const handleSignInWithDiscordPress = async () => {
try {
const redirectUrl = AuthSession.makeRedirectUri({
path: "/oauth-native-callback",
});
await signIn.create({
strategy: "oauth_discord",
redirectUrl,
});
const {
firstFactorVerification: { externalVerificationRedirectURL },
} = signIn;
const result = await AuthSession.startAsync({
authUrl: externalVerificationRedirectURL?.toString() || "",
returnUrl: redirectUrl,
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { type, params } = result || {};
if (type !== "success") {
throw "Something went wrong during the OAuth flow. Try again.";
}

You may notice that we have an eslint to disable the checks on the next line. There is an assumption in this example that it will always be successful, but you can use the following AuthSession documentation to implement anything you may want to handle.

We now need to retrieve rotatingTokenNonce and reload our signIn object. This will allow us to get the sessionId and sign the user in.

import { useSignIn } from "@clerk/clerk-expo";
import React from "react";
import { Button, View } from "react-native";
import * as AuthSession from "expo-auth-session";
const SignInWithOAuth = () => {
const { isLoaded, signIn, setSession } = useSignIn();
if (!isLoaded) return null;
const handleSignInWithDiscordPress = async () => {
try {
const redirectUrl = AuthSession.makeRedirectUri({
path: "/oauth-native-callback",
});
await signIn.create({
strategy: "oauth_discord",
redirectUrl,
});
const {
firstFactorVerification: { externalVerificationRedirectURL },
} = signIn;
const result = await AuthSession.startAsync({
authUrl: externalVerificationRedirectURL.toString(),
returnUrl: redirectUrl,
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { type, params } = result || {};
console.log;
if (type !== "success") {
throw "Something went wrong during the OAuth flow. Try again.";
}
// Get the rotatingTokenNonce from the redirect URL parameters
const { rotating_token_nonce: rotatingTokenNonce } = params;
await signIn.reload({ rotatingTokenNonce });

Finally we can retrieve the createdSessionId from the signIn object and set that to our current session. This will let us know that the user is signed in with a valid session.

import { useSignIn } from "@clerk/clerk-expo";
import React from "react";
import { Button, View } from "react-native";
import * as AuthSession from "expo-auth-session";
const SignInWithOAuth = () => {
const { isLoaded, signIn, setSession } = useSignIn();
if (!isLoaded) return null;
const handleSignInWithDiscordPress = async () => {
try {
const redirectUrl = AuthSession.makeRedirectUri({
path: "/oauth-native-callback",
});
await signIn.create({
strategy: "oauth_discord",
redirectUrl,
});
const {
firstFactorVerification: { externalVerificationRedirectURL },
} = signIn;
const result = await AuthSession.startAsync({
authUrl: externalVerificationRedirectURL?.toString() || "",
returnUrl: redirectUrl,
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { type, params } = result || {};
if (type !== "success") {
throw "Something went wrong during the OAuth flow. Try again.";
}
// Get the rotatingTokenNonce from the redirect URL parameters
const { rotating_token_nonce: rotatingTokenNonce } = params;
await signIn.reload({ rotatingTokenNonce });
const { createdSessionId } = signIn;
if (!createdSessionId) {
throw "Something went wrong during the Sign in OAuth flow. Please ensure that all sign in requirements are met.";
}
await setSession(createdSessionId);
return;
}

Finally we can add a catch for anything that might go wrong that we aren’t handling and return the error.

import { useSignIn } from "@clerk/clerk-expo";
import React from "react";
import { Button, View } from "react-native";
import * as AuthSession from "expo-auth-session";
const SignInWithOAuth = () => {
const { isLoaded, signIn, setSession } = useSignIn();
if (!isLoaded) return null;
const handleSignInWithDiscordPress = async () => {
try {
const redirectUrl = AuthSession.makeRedirectUri({
path: "/oauth-native-callback",
});
await signIn.create({
strategy: "oauth_discord",
redirectUrl,
});
const {
firstFactorVerification: { externalVerificationRedirectURL },
} = signIn;
const result = await AuthSession.startAsync({
authUrl: externalVerificationRedirectURL?.toString() || "",
returnUrl: redirectUrl,
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { type, params } = result || {};
if (type !== "success") {
throw "Something went wrong during the OAuth flow. Try again.";
}
// Get the rotatingTokenNonce from the redirect URL parameters
const { rotating_token_nonce: rotatingTokenNonce } = params;
await signIn.reload({ rotatingTokenNonce });
const { createdSessionId } = signIn;
if (!createdSessionId) {
throw "Something went wrong during the Sign in OAuth flow. Please ensure that all sign in requirements are met.";
}
await setSession(createdSessionId);
return;
}catch (err) {
console.log(JSON.stringify(err, null, 2));
console.log("error signing in", err);
}
};

Our sign in method is now complete, so we can create a simple UI that, on touch, will attempt a sign in.

return (
<View className="rounded-lg border-2 border-gray-500 p-4">
<Button
title="Sign in with Discord"
onPress={handleSignInWithDiscordPress}
/>
</View>
);

Our Sign In component is now complete below is the full code. We will use this for a Sign Up component for anyone who doesn’t have an account yet for our application.

1
import { useSignIn } from "@clerk/clerk-expo";
2
import React from "react";
3
import { Button, View } from "react-native";
4
5
import * as AuthSession from "expo-auth-session";
6
7
const SignInWithOAuth = () => {
8
const { isLoaded, signIn, setSession } = useSignIn();
9
10
if (!isLoaded) return null;
11
12
const handleSignInWithDiscordPress = async () => {
13
try {
14
const redirectUrl = AuthSession.makeRedirectUri({
15
path: "/oauth-native-callback",
16
});
17
18
await signIn.create({
19
strategy: "oauth_discord",
20
redirectUrl,
21
});
22
23
const {
24
firstFactorVerification: { externalVerificationRedirectURL },
25
} = signIn;
26
27
const result = await AuthSession.startAsync({
28
authUrl: externalVerificationRedirectURL.toString(),
29
returnUrl: redirectUrl,
30
});
31
32
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
33
// @ts-ignore
34
const { type, params } = result || {};
35
console.log;
36
if (type !== "success") {
37
throw "Something went wrong during the OAuth flow. Try again.";
38
}
39
40
// Get the rotatingTokenNonce from the redirect URL parameters
41
const { rotating_token_nonce: rotatingTokenNonce } = params;
42
43
await signIn.reload({ rotatingTokenNonce });
44
45
const { createdSessionId } = signIn;
46
47
if (!createdSessionId) {
48
throw "Something went wrong during the Sign in OAuth flow. Please ensure that all sign in requirements are met.";
49
}
50
51
await setSession(createdSessionId);
52
53
return;
54
} catch (err) {
55
console.log(JSON.stringify(err, null, 2));
56
console.log("error signing in", err);
57
}
58
};
59
60
return (
61
<View className="rounded-lg border-2 border-gray-500 p-4">
62
<Button
63
title="Sign in with Discord"
64
onPress={handleSignInWithDiscordPress}
65
/>
66
</View>
67
);
68
};
69
70
export default SignInWithOAuth;

Create a Sign Up component

The good news is that the sign in component and the sign up component is very similar and 99% of the code we created can be reused and swapped for useSignUp hook. To save you from reading more content, here is the code.

1
import { useSignUp } from "@clerk/clerk-expo";
2
import React from "react";
3
import { Button, View } from "react-native";
4
5
import * as AuthSession from "expo-auth-session";
6
7
const SignUpWithOAuth = () => {
8
const { isLoaded, signUp, setSession } = useSignUp();
9
10
if (!isLoaded) return null;
11
12
const handleSignUpWithDiscordPress = async () => {
13
try {
14
const redirectUrl = AuthSession.makeRedirectUri({
15
path: "/oauth-native-callback",
16
});
17
18
await signUp.create({
19
strategy: "oauth_discord",
20
redirectUrl,
21
});
22
23
const {
24
verifications: {
25
externalAccount: { externalVerificationRedirectURL },
26
},
27
} = signUp;
28
29
const result = await AuthSession.startAsync({
30
authUrl: externalVerificationRedirectURL!.toString(),
31
returnUrl: redirectUrl,
32
});
33
console.log(result);
34
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
35
// @ts-ignore
36
const { type, params } = result || {};
37
console.log;
38
if (type !== "success") {
39
throw "Something went wrong during the OAuth flow. Try again.";
40
}
41
42
// Get the rotatingTokenNonce from the redirect URL parameters
43
const { rotating_token_nonce: rotatingTokenNonce } = params;
44
45
await signUp.reload({ rotatingTokenNonce });
46
const { createdSessionId } = signUp;
47
48
if (!createdSessionId) {
49
throw "Something went wrong during the Sign up OAuth flow. Please ensure that all sign in requirements are met.";
50
}
51
52
await setSession(createdSessionId);
53
54
return;
55
} catch (err) {
56
console.log(JSON.stringify(err, null, 2));
57
console.log("error signing up", err);
58
}
59
};
60
61
return (
62
<View className="my-8 rounded-lg border-2 border-gray-500 p-4">
63
<Button
64
title="Sign Up with Discord"
65
onPress={handleSignUpWithDiscordPress}
66
/>
67
</View>
68
);
69
};
70
71
export default SignUpWithOAuth;

Creating a Sign in, Sign Up screen

We now need to use our components in our application. Under the screens folder, create a new file called signInSignUp.tsx and paste the following code. We are displaying the components we created so the code below is generic React Native code.

1
import React from "react";
2
3
import { View, SafeAreaView } from "react-native";
4
5
import SignInWithOAuth from "../components/SignInWithOAuth";
6
import SignUpWithOAuth from "../components/SignUpWithOAuth";
7
8
export const SignInSignUpScreen = () => {
9
return (
10
<SafeAreaView className="bg-[#2e026d] bg-gradient-to-b from-[#2e026d] to-[#15162c]">
11
<View className="h-full w-full p-4">
12
<SignUpWithOAuth />
13
<SignInWithOAuth />
14
</View>
15
</SafeAreaView>
16
);
17
};

Updating _app.tsx

We can now update our SignedOut control component to use the SignInSignUpScreen so if a user doesn’t have a valid session and is not signed in, they will be able to sign in.

1
import { StatusBar } from "expo-status-bar";
2
import React from "react";
3
import { SafeAreaProvider } from "react-native-safe-area-context";
4
import { TRPCProvider } from "./utils/trpc";
5
6
import { HomeScreen } from "./screens/home";
7
import { SignInSignUpScreen } from "./screens/signInSignUp";
8
import { ClerkProvider, SignedIn, SignedOut } from "@clerk/clerk-expo";
9
import { tokenCache } from "./utils/cache";
10
11
// Find this in your Dashboard.
12
const clerk_frontend_api = "YOUR_API_KEY";
13
14
export const App = () => {
15
return (
16
<ClerkProvider frontendApi={clerk_frontend_api} tokenCache={tokenCache}>
17
<SignedIn>
18
<TRPCProvider>
19
<SafeAreaProvider>
20
<HomeScreen />
21
<StatusBar />
22
</SafeAreaProvider>
23
</TRPCProvider>
24
</SignedIn>
25
<SignedOut>
26
<SignInSignUpScreen />
27
</SignedOut>
28
</ClerkProvider>
29
);
30
};

Updating TRPC client

The TRPC client found under utils/trpc needs a very small update. As part of TRPC, you can provide headers as part of httpBatchLink . We can get the JWT token by using getToken, which is part of the useAuth hook.

First, add the import import { useAuth } from "@clerk/clerk-expo"; , then, inside our TRPCProvider, add the getToken code before the client.

export const TRPCProvider: React.FC<{
children: React.ReactNode;
}> = ({ children }) => {
const { getToken } = useAuth();
const [queryClient] = React.useState(() => new QueryClient());
......

Then finally, add the Authorization header to our httpBatchLink

async headers() {
const authToken = await getToken();
return {
Authorization: authToken,
};
},

This will allow you to send a valid token with your requests to the TRPC backend. Below is the full code:

1
import { createTRPCReact } from "@trpc/react-query";
2
import type { AppRouter } from "@acme/api";
3
/**
4
* Extend this function when going to production by
5
* setting the baseUrl to your production API URL.
6
*/
7
import Constants from "expo-constants";
8
/**
9
* A wrapper for your app that provides the TRPC context.
10
* Use only in _app.tsx
11
*/
12
import React from "react";
13
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
14
import { httpBatchLink } from "@trpc/client";
15
import { transformer } from "@acme/api/transformer";
16
import { useAuth } from "@clerk/clerk-expo";
17
18
/**
19
* A set of typesafe hooks for consuming your API.
20
*/
21
export const trpc = createTRPCReact<AppRouter>();
22
23
const getBaseUrl = () => {
24
/**
25
* Gets the IP address of your host-machine. If it cannot automatically find it,
26
* you'll have to manually set it. NOTE: Port 3000 should work for most but confirm
27
* you don't have anything else running on it, or you'd have to change it.
28
*/
29
const localhost = Constants.manifest?.debuggerHost?.split(":")[0];
30
if (!localhost)
31
throw new Error("failed to get localhost, configure it manually");
32
return `http://${localhost}:3000`;
33
};
34
35
export const TRPCProvider: React.FC<{
36
children: React.ReactNode;
37
}> = ({ children }) => {
38
const { getToken } = useAuth();
39
const [queryClient] = React.useState(() => new QueryClient());
40
const [trpcClient] = React.useState(() =>
41
trpc.createClient({
42
transformer,
43
links: [
44
httpBatchLink({
45
async headers() {
46
const authToken = await getToken();
47
return {
48
Authorization: authToken,
49
};
50
},
51
url: `${getBaseUrl()}/api/trpc`,
52
}),
53
],
54
}),
55
);
56
57
return (
58
<trpc.Provider client={trpcClient} queryClient={queryClient}>
59
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
60
</trpc.Provider>
61
);
62
};

Go ahead and test everything. At this point, you have a working application that uses TRPC

Final Updates to our TRPC API

The final update here is to update the post router to use a protectedProcedure for creation so that when a user uses the Expo application, they will need to be logged in to create a new post. Open the post.ts under /packages/api/src/router and update the create to use protectedProcedure .

1
import { router, publicProcedure, protectedProcedure } from "../trpc";
2
import { z } from "zod";
3
4
export const postRouter = router({
5
all: publicProcedure.query(({ ctx }) => {
6
return ctx.prisma.post.findMany();
7
}),
8
byId: publicProcedure.input(z.string()).query(({ ctx, input }) => {
9
return ctx.prisma.post.findFirst({ where: { id: input } });
10
}),
11
create: protectedProcedure
12
.input(z.object({ title: z.string(), content: z.string() }))
13
.mutation(({ ctx, input }) => {
14
return ctx.prisma.post.create({ data: input });
15
}),
16
});

Next Steps

Now you have a working T3 Turbo application that has authentication both in Next.js and Expo with protected routes. Here are some next steps you might want to implement:

  • Additional login methods for Expo ( more social logins or email and password screen)
  • Use one of our integrations to use a database, such as Fauna, Supabase, or Firebase.
  • Join our Discord
Clerk's logo

Start now,
no strings attached

Start completely free for up to 10,000 monthly active users and up to 100 monthly active orgs. No credit card required.

Start Building

Pricing built for
businesses of all sizes.

Learn more about our transparent per-user costs to estimate how much your company could save by implementing Clerk.

View pricing
Clerk's logo

Newsletter!

The latest news and updates from Clerk, sent to your inbox.

Clerk logo

Clerk - Complete User Management

TwitterLinkedInGitHubDiscordFacebook

© 2023 Clerk Inc.


product
Components

© 2023 Clerk Inc.