Skip to content

Instantly share code, notes, and snippets.

@cwefso
Last active January 19, 2022 22:30
Show Gist options
  • Save cwefso/f0eed5fc37a7bf23e3de61067d4137aa to your computer and use it in GitHub Desktop.
Save cwefso/f0eed5fc37a7bf23e3de61067d4137aa to your computer and use it in GitHub Desktop.
Clerk Integration - Turing

Clerk: Authentication and User Management

Authentication is always important, but it can take a lot of time to integrate into a project, especially for someone at the beginning of their developer journey. Clerk provides out of the box authentication and user management that can be set up in minutes, allowing you to focus on what makes your application unique. This guide will show you how to start a new application using Clerk to manage your users and their permissions. We're going to walk through how to use Clerk with a React application, but Clerk also has integrations for Next.js, Gatsby, Node/Express, React Native and Expo. Check out the docs for more information.

Create Clerk Application

The first thing you want to do is go to the Clerk Dashboard and create a new account. Then click Add application to create your first Clerk App. Clerk's free tier supports up to 500 monthly active users.

Clerk new account signup

Name your application and select which SSO (Single Sign-On) methods you want your user to be able to select to log in to your app. You can also select if you want your user to have a password, or if you'd like them to get an email or SMS with a code that they will use to log in. For the sake of this tutorial we will just go with the options already selected.

Create a React App

Clerk can be integrated easily into an existing application, but for the simplicity's sake we'll be starting fresh with a new React application. Open your terminal and run the command:

$ npx create-react-app clerk-starter-app

If you have any interest in using Typescript, you can add --typescript to the end of the command above. Clerk is written in Typescript so it will work without any extra configuration.

To install Clerk into your new app:

$ cd clerk-starter-app
$ npm install @clerk/clerk-react

Setting up your environment

To get Clerk working you'll need to set up the CLERK_FRONTEND_API environment variable.

If you haven't used environment variables yet, take a look at this Mod 4 lesson plan for more context.

Create a file named .env.local in the root directory of your application. Any variables that you put in this file that start with REACT_APP can be accessed in your app with process.env.REACT_APP_VARIABLE_NAME. You'll need to create a variable called REACT_APP_CLERK_FRONTEND_API.

Next return to the Clerk Dashboard and look on the homepage for your Frontend API Key. It should look something like this:

Clerk new account signup

Copy this key and return to your application. Assign the environment variable you created in .env.local to the key you just copied. It should look like:

REACT_APP_CLERK_FRONTEND_API=your-frontend-api-key

Clerk is installed!

You can now run:

$ npm start

The development server is now running at http://localhost:3000

Adding <ClerkProvider />

You'll next want to wrap your app with the <ClerkProvider /> component. To do this you'll need to navigate to src/App.jsx and make the following changes:

import logo from "./logo.svg";
import "./App.css";
// Import ClerkProvider
import { ClerkProvider } from "@clerk/clerk-react";

// Get the Frontend API from the environment
const frontendApi = process.env.REACT_APP_CLERK_FRONTEND_API;

function App() {
return (
    // Wrap your entire app with ClerkProvider
    // Don't forget to pass the frontendApi prop
    <ClerkProvider  frontendApi={frontendApi}>
	<Hello />
    </ClerkProvider>
    );
}

function  Hello()  {
return  <div>Hello from Clerk</div>;
}

export default App;

Adding a router

Install React Router

<ClerkProvider/> also accepts a navigate prop that enables Clerk to navigate inside your application without a full page reload. Most React apps use the popular react-router-dom router, which is also what we'll be using for this guide. Install it by running the following command:

$ npm i react-router-dom

To learn more about React Router check out this Mod 3 lesson

Navigate to src/index.jsx and make the following changes to your code:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

// Import the BrowserRouter from the react-router-dom package
import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <React.StrictMode>
    {/* Wrap your App component with the Router */}
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

reportWebVitals();

Give Clerk access to your router

You can give Clerk access to your router by using the useNavigate hook provided by react-router-dom and passing the navigate prop to the <ClerkProvider /> component in src/App.jsx. Make the following changes to your code:

import React from "react";
import "./App.css";
import { ClerkProvider } from "@clerk/clerk-react";
// import the useNavigate hook
import { useNavigate } from "react-router-dom";

const frontendApi = process.env.REACT_APP_CLERK_FRONTEND_API;

function App() {
  const navigate = useNavigate();

  return (
    //  Pass the push method to the navigate prop
    <ClerkProvider frontendApi={frontendApi} navigate={(to) => navigate(to)}>
      <Hello />
    </ClerkProvider>
  );
}

function  Hello()  {
	return  <div>Hello from Clerk</div>;
}

export default App;

Control Components

fun begins

Clerk makes it incredibly easy to require users to sign in before they can see restricted parts of your application. The Control Components are:

With these components Clerk takes all of the complication out of signing your users in and out. If an active user is signed it, anything wrapped in the <SignedIn/> component will be shown to the user. If no active user is signed in, anything wrapped in the <SignedOut/> component will be shown. The <RedirectToSignIn/> component will redirect the user to log in through Clerk's login form.

Let's take a look at how this works in action. In src/App.jsx modify the code with these changes:

import React from "react";
import "./App.css";
import {
  ClerkProvider,
  SignedIn,
  SignedOut,
  UserButton,
  useUser,
  RedirectToSignIn,
} from "@clerk/clerk-react";
import { useNavigate } from "react-router-dom";

const frontendApi = process.env.REACT_APP_CLERK_FRONTEND_API;

function App() {
    const navigate = useNavigate();
    // If the current route is listed as public, render it directly
    // Otherwise, use Clerk to require authentication
    return (
        <ClerkProvider frontendApi={frontendApi} navigate={(to) => navigate(to)}>
          <SignedIn>
            <Hello />
          </SignedIn>
          <SignedOut>
           <RedirectToSignIn />
          </SignedOut>
        </ClerkProvider>
   );
}

function  Hello()  {
    return  <div>Hello from Clerk</div>;
}

export default App;

Now when you visit https://localhost:3000 to see your page - you'll immediately get redirected to the Clerk Hosted Sign In page:

Clerk sign in

You can customize the look of this form by going to the Clerk Dashboard, clicking Customization and selecting Theme

Users

Your app is now fully integrated with Clerk. It's time to access the User object and to say hello to our user!

So far we've had this simple <Hello /> component as a placeholder. Let's use that component to access the User Object. In src/App.jsx make these changes to the <Hello /> component:

function Hello() {
  // Get the user's first name
  const { firstName } = useUser();

  return (
    <div className="App-header">
      {/* Mount the UserButton component */}
      <UserButton />
      <div>Hello, {firstName}!</div>
    </div>
  );
}

export default App;

Visit https://localhost:3000 again to see your page. If you haven't signed in yet, you will be redirected to the sign in page. Sign in using your preferred method and the home page will become accessible:

Clerk signed in

Originally 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 is used to render this familiar user button UI. It renders a clickable user avatar - when clicked, the full UI opens as a popup.

Take some time to explore the User object.

const user = useUser()

console.log("user", user)

If you need to store new information on the User Object that is specific to your application, you can use the metadata attributes. For more information on which attribute to use, check out the Clerk Docs on the User-Object

You did it!!

You now have a fully working React + Clerk application! Users can now log in and out of your application with whichever SSO options you prefer, and you can manage your users from the Clerk dashboard for your project.

Now you have a solid foundation to build out the rest of your app!

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment