Initialise Clerk Frontend from scratch

  1. Create a Clerk account and setup a new application in the dashboard and select your auth options
  2. install Clerk on the frontend:
    1. npm install @clerk/clerk-react
    2. 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.
  3. 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") 
	}
  1. Make sure React Router DOM is installed (npm i react-router-dom)

  2. 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>,
)
  1. 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

  1. Install @clerk/express
  2. Set your Clerk API keys
    1. Add the publishable key and secret key to your .env file.
      • When you use clerkMiddleware() or requireAuth(), the SDK uses these keys behind the scenes to:
    • Verify the authenticity of session tokens
    • Make API calls to Clerk’s services to fetch user data
    • Manage authentication states
  • 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.
  1. Add clerkMiddleware() to your application
    1. 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.
  2. Protect your routes using requireAuth()
    1. This middleware functions similarly to clerkMiddleware(), but also protects your routes by redirecting unauthenticated users to the sign-in page.
    2. 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, the req.auth object is used to get the userId, which is passed to clerkClient.users.getUser() to fetch the current user’s User object.
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.
  • isLoaded boolean
    • A boolean that until Clerk loads and initializes, will be set to false. Once Clerk loads, isLoaded will be set to true.
  • user User
    • The User object for the currently active user. If the user is not signed in, user will be null.

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

PropertyTypeDescription
idstringA unique identifier for the user.
firstNamestring | nullThe user’s first name.
lastNamestring | nullThe user’s last name.
fullNamestring | nullThe user’s full name.
usernamestring | nullThe user’s username.

Profile Image

PropertyTypeDescription
hasImagebooleanA 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.
imageUrlstringHolds the default avatar or user’s uploaded profile image. Compatible with Clerk’s Image Optimization.

Authentication Methods

PropertyTypeDescription
passkeysPasskeyResource[] | nullAn array of passkeys associated with the user’s account.
passwordEnabledbooleanA boolean indicating whether the user has a password on their account.
totpEnabledbooleanA boolean indicating whether the user has enabled TOTP by generating a TOTP secret and verifying it via an authenticator app.
twoFactorEnabledbooleanA boolean indicating whether the user has enabled two-factor authentication.
backupCodeEnabledbooleanA boolean indicating whether the user has enabled Backup codes.

Contact Information

Email

PropertyTypeDescription
primaryEmailAddressEmailAddress | nullInformation about the user’s primary email address.
primaryEmailAddressIdstring | nullThe unique identifier for the EmailAddress that the user has set as primary.
emailAddressesEmailAddress[]An array of all the EmailAddress objects associated with the user. Includes the primary.
hasVerifiedEmailAddressbooleanA getter boolean to check if the user has verified an email address.

Phone

PropertyTypeDescription
primaryPhoneNumberPhoneNumber | nullInformation about the user’s primary phone number.
primaryPhoneNumberIdstring | nullThe unique identifier for the PhoneNumber that the user has set as primary.
phoneNumbersPhoneNumber[]An array of all the PhoneNumber objects associated with the user. Includes the primary.
hasVerifiedPhoneNumberbooleanA getter boolean to check if the user has verified a phone number.

Web3 & External Accounts

PropertyTypeDescription
primaryWeb3WalletIdstring | nullThe unique identifier for the Web3Wallet that the user signed up with.
primaryWeb3WalletWeb3Wallet | nullThe Web3Wallet that the user signed up with.
web3WalletsWeb3Wallet[]An array of all the Web3Wallet objects associated with the user. Includes the primary.
externalAccountsExternalAccount[]An array of all the ExternalAccount objects associated with the user via OAuth. Note: This includes both verified & unverified external accounts.
verifiedExternalAccountsExternalAccount[]A getter for the user’s list of verified external accounts.
unverifiedExternalAccountsExternalAccount[]A getter for the user’s list of unverified external accounts.
samlAccountsSamlAccount[]An experimental list of saml accounts associated with the user.

Organization

PropertyTypeDescription
organizationMembershipsOrganizationMembership[]A list of OrganizationMemberships representing the list of organizations the user is member with.
createOrganizationEnabledbooleanA boolean indicating whether the organization creation is enabled for the user or not.
createOrganizationsLimitnumberAn 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

PropertyTypeDescription
publicMetadata{[string]: any} | nullMetadata that can be read from the Frontend API and Backend API and can be set only from the Backend API.
privateMetadata{[string]: any} | nullMetadata that can be read and set only from the Backend API.
unsafeMetadata{[string]: any} | nullMetadata 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

PropertyTypeDescription
lastSignInAtDateDate when the user last signed in. May be empty if the user has never signed in.
createdAtDateDate when the user was first created.
updatedAtDateDate of the last time the user was updated.

Account Management

PropertyTypeDescription
deleteSelfEnabledbooleanA boolean indicating whether the user is able to delete their own account or not.

useClerk()

useAuth()

useSignIn()

useSignOut()

useSession()