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>
}