Initialise Clerk Frontend from scratch
- Create a Clerk account and setup a new application in the dashboard and select your auth options
- install Clerk on the frontend:
- npm install @clerk/clerk-react
- Add the Clerk Publishable keys to your .env.local or create the file if it doesn’t exist. Retrieve these keys anytime from the API keys page.
- Add publishable key to your main.tsx file
// Import your publishable key
const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY
if (!PUBLISHABLE_KEY) {
throw new Error("Missing Publishable Key")
}
-
Make sure React Router DOM is installed (npm i react-router-dom)
-
All Clerk hooks and components must be children of the ClerkProvider component, which provides active session and user context. Ensure you wrap your app in the ClerkProvider component. You must pass your publishable key as a prop to the ClerkProvider component in main.tsx.
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import { ClerkProvider } from '@clerk/clerk-react'
// Import your publishable key
const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY
if (!PUBLISHABLE_KEY) {
throw new Error("Missing Publishable Key")
}
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<ClerkProvider publishableKey={PUBLISHABLE_KEY} afterSignOutUrl="/">
<App />
</ClerkProvider>
</React.StrictMode>,
)
- Create a header with Clerk components in App.tsx
- You can control which content signed in and signed out users can see with Clerk’s prebuilt components. The code below will create a header for your users to sign in or out.
import { SignedIn, SignedOut, SignInButton, UserButton } from "@clerk/clerk-react";
export default function App() {
return (
<header>
<SignedOut> // Children of this can only be seen when signed out.
<SignInButton /> // Unstyled component links to the sign-in page or displays the sign-in modal.
</SignedOut>
<SignedIn> // Children of this can only be seen when signed in.
<UserButton /> // Pre-built/styled to show the signed in avatar
</SignedIn>
</header>
);
}
Part 2. Add React Router to your Clerk-powered React application
Part 3.
Initialise Clerk Backend from scratch**
Express quickstart guide: https://clerk.com/docs/quickstarts/express
- Install
@clerk/express
- Set your Clerk API keys
- Add the publishable key and secret key to your
.env
file. -
- When you use
clerkMiddleware()
orrequireAuth()
, the SDK uses these keys behind the scenes to:
- When you use
- Verify the authenticity of session tokens
- Make API calls to Clerk’s services to fetch user data
- Manage authentication states
- Add the publishable key and secret key to your
- API Calls: When you use functions like
clerkClient.users.getUser()
, the SDK uses your secret key to authenticate these API calls to Clerk’s backend services.
- Add
clerkMiddleware()
to your application- The clerkMiddleware() function checks the request’s cookies and headers for a session JWT and, if found, attaches the Auth object to the request object under the auth key.
- Protect your routes using
requireAuth()
- This middleware functions similarly to
clerkMiddleware()
, but also protects your routes by redirecting unauthenticated users to the sign-in page. requireAuth()
is used to protect the/protected
route. If the user is not authenticated, they are redirected to the ‘/sign-in’ route. If the user is authenticated, thereq.auth
object is used to get theuserId
, which is passed toclerkClient.users.getUser()
to fetch the current user’sUser
object.
- This middleware functions similarly to
import 'dotenv/config'
import express from 'express'
import { clerkClient, requireAuth } from '@clerk/express'
const app = express()
app.get('/protected', requireAuth({ signInUrl: '/sign-in' }), (req, res) => {
const { userId } = req.auth
const user = await clerkClient.users.getUser(userId)
return res.json({ user })
})
app.get('/sign-in', (req, res) => {
// Assuming you have a template engine installed and are using a Clerk JavaScript SDK on this page
res.render('sign-in')
})
app.listen(3000, () => {
console.log(`Example app listening at http://localhost:${PORT}`)
})
Using Clerk with NextJS
Useful Methods
The User object
The User
object holds all of the information for a single user of your application and provides a set of methods to manage their account. Each user has a unique authentication identifier which might be their email address, phone number, or a username.
A user can be contacted at their primary email address or primary phone number. They can have more than one registered email address, but only one of them will be their primary email address. This goes for phone numbers as well; a user can have more than one, but only one phone number will be their primary. At the same time, a user can also have one or more external accounts by connecting to social providers such as Google, Apple, Facebook, and many more.
Finally, a User
object holds profile data like the user’s name, profile picture, and a set of metadatathat can be used internally to store arbitrary information.
Useful methods:
update()
Updates the user’s attributes. Use this method to save information you collected about the user.
delete()
deletes the user
reload()
This method is useful when you want to refresh the user’s data after performing some form of mutation.
all methods can be found here: https://clerk.com/docs/references/javascript/user/user
Useful Hooks
useUser()
Access the current user’s User
object, which holds all of the information for a single user of your application and provides a set of methods to manage their account.
Options:
isSignedIn
boolean
- A boolean that returns
true
if the user is signed in.
- A boolean that returns
isLoaded
boolean
- A boolean that until Clerk loads and initializes, will be set to
false
. Once Clerk loads,isLoaded
will be set totrue
.
- A boolean that until Clerk loads and initializes, will be set to
user
User
- The
User
object for the currently active user. If the user is not signed in,user
will benull
.
- The
Retrieve the current user data with the useUser()
hook
import { useUser } from '@clerk/clerk-react'
export default function Home() {
const { isSignedIn, user, isLoaded } = useUser()
if (!isLoaded) {
// Handle loading state however you like
return null
}
if (isSignedIn) {
return <div>Hello {user.fullName}!</div>
}
return <div>Not signed in</div>
}
Update the current user data with the useUser()
hook
Reload user data with the useUser()
hook
Reference Table
Property | Type | Description |
---|---|---|
id | string | A unique identifier for the user. |
firstName | string | null | The user’s first name. |
lastName | string | null | The user’s last name. |
fullName | string | null | The user’s full name. |
username | string | null | The user’s username. |
Profile Image
Property | Type | Description |
---|---|---|
hasImage | boolean | A getter boolean to check if the user has uploaded an image or one was copied from OAuth. Returns false if Clerk is displaying an avatar for the user. |
imageUrl | string | Holds the default avatar or user’s uploaded profile image. Compatible with Clerk’s Image Optimization. |
Authentication Methods
Property | Type | Description |
---|---|---|
passkeys | PasskeyResource[] | null | An array of passkeys associated with the user’s account. |
passwordEnabled | boolean | A boolean indicating whether the user has a password on their account. |
totpEnabled | boolean | A boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app. |
twoFactorEnabled | boolean | A boolean indicating whether the user has enabled two-factor authentication. |
backupCodeEnabled | boolean | A boolean indicating whether the user has enabled Backup codes. |
Contact Information
Property | Type | Description |
---|---|---|
primaryEmailAddress | EmailAddress | null | Information about the user’s primary email address. |
primaryEmailAddressId | string | null | The unique identifier for the EmailAddress that the user has set as primary. |
emailAddresses | EmailAddress[] | An array of all the EmailAddress objects associated with the user. Includes the primary. |
hasVerifiedEmailAddress | boolean | A getter boolean to check if the user has verified an email address. |
Phone
Property | Type | Description |
---|---|---|
primaryPhoneNumber | PhoneNumber | null | Information about the user’s primary phone number. |
primaryPhoneNumberId | string | null | The unique identifier for the PhoneNumber that the user has set as primary. |
phoneNumbers | PhoneNumber[] | An array of all the PhoneNumber objects associated with the user. Includes the primary. |
hasVerifiedPhoneNumber | boolean | A getter boolean to check if the user has verified a phone number. |
Web3 & External Accounts
Property | Type | Description |
---|---|---|
primaryWeb3WalletId | string | null | The unique identifier for the Web3Wallet that the user signed up with. |
primaryWeb3Wallet | Web3Wallet | null | The Web3Wallet that the user signed up with. |
web3Wallets | Web3Wallet[] | An array of all the Web3Wallet objects associated with the user. Includes the primary. |
externalAccounts | ExternalAccount[] | An array of all the ExternalAccount objects associated with the user via OAuth. Note: This includes both verified & unverified external accounts. |
verifiedExternalAccounts | ExternalAccount[] | A getter for the user’s list of verified external accounts. |
unverifiedExternalAccounts | ExternalAccount[] | A getter for the user’s list of unverified external accounts. |
samlAccounts | SamlAccount[] | An experimental list of saml accounts associated with the user. |
Organization
Property | Type | Description |
---|---|---|
organizationMemberships | OrganizationMembership[] | A list of OrganizationMemberships representing the list of organizations the user is member with. |
createOrganizationEnabled | boolean | A boolean indicating whether the organization creation is enabled for the user or not. |
createOrganizationsLimit | number | An integer indicating the number of organizations that can be created by the user. If the value is 0, then the user can create unlimited organizations. Default is null. |
Metadata
Property | Type | Description |
---|---|---|
publicMetadata | {[string]: any} | null | Metadata that can be read from the Frontend API and Backend API and can be set only from the Backend API. |
privateMetadata | {[string]: any} | null | Metadata that can be read and set only from the Backend API. |
unsafeMetadata | {[string]: any} | null | Metadata that can be read and set from the Frontend API. One common use case for this attribute is to implement custom fields that will be attached to the User object. |
Timestamps
Property | Type | Description |
---|---|---|
lastSignInAt | Date | Date when the user last signed in. May be empty if the user has never signed in. |
createdAt | Date | Date when the user was first created. |
updatedAt | Date | Date of the last time the user was updated. |
Account Management
Property | Type | Description |
---|---|---|
deleteSelfEnabled | boolean | A boolean indicating whether the user is able to delete their own account or not. |