# Clerk Blog — Page 12

# Building a Custom User Profile with Clerk
URL: https://clerk.com/blog/building-custom-user-profile-with-clerk.md
Date: 2022-08-03
Category: Guides
Description: Authentication is one of the most critical functions of securing your applications; however, it's also one of the most challenging functions to implement.

Failing to implement a proper authentication system can make your application vulnerable and your users' information open to potential hackers.

If you don't want to get into the technicalities of implementing an authentication system from scratch, [Clerk](/) is your solution. Clerk provides built-in components for your application that can be easily integrated into your frontend application, and it supports most of the popular frameworks, like [React](https://reactjs.org), [Next.js](https://nextjs.org), and [Gatsby](https://www.gatsbyjs.com).

Clerk can be beneficial for your customer identity management. You can easily manage your user sessions, devices, and profiles from the Clerk dashboard. Moreover, you can easily integrate Clerk with services like [Firebase](https://firebase.google.com) or [Google Analytics](https://marketingplatform.google.com/about/analytics).

In addition, Clerk makes integrating authentication to your existing application simple since it provides built-in hooks for adding authentication. You can implement social sign-in, password-based authentication, or Web3 logins easily using Clerk. You can also extend your functionalities and create custom components and user profiles using their SDK and APIs.

In this article, you'll see how Clerk authentication can be implemented in your Next.js application and how you can implement the Clerk built-in components for user profiles. You'll also learn how to create custom user profiles for your users and update users' profiles using your custom components.

## What Is Clerk?

Clerk is an all-in-one solution for your authentication and user management needs. It provides features like password-based or social sign-in, [passwordless login using magic links](/blog/magic-links) or email, and SMS passcodes. It also provides a user management dashboard, user analytics, allow/block list, rate limiting, and [more](/#home-features).

With Clerk, you can set up a complete [user management system within ten minutes](https://www.youtube.com/watch?v=mywtHZcrYfE\&feature=emb_imp_woyt). Clerk can seamlessly integrate with popular technologies, including React, Next.js, Gatsby, [RedwoodJS](https://redwoodjs.com), [Remix](https://remix.run), [Node.js](https://nodejs.org/en), and [Go](https://go.dev).

For popular frontend frameworks, like React, Remix, RedwoodJS, or Gatsby, Clerk has created well-designed components for login, sign-up, the user profile, and the user button. However, it's not limited to built-in components. You can always create custom components with the help of hooks provided by the Clerk SDK.

Because Clerk provides you with frontend SDK, API, and backend APIs for developing custom pages for your users, building a customer user profile is easy.

## Building a Custom User Profile Using Clerk

This article aims to show how you can create custom user profiles for your Next.js applications and how to implement the built-in components. To do this, you'll use the [Clerk SDK for Next.js](/nextjs-authentication).

The basic flow of the application is shown in the following GIF:

### Prerequisites

Before you build your custom user profiles with Clerk, you need to satisfy a few prerequisites, including the following:

- Create a Clerk [account](https://dashboard.clerk.com/sign-up).
- Have a basic understanding of Next.js. To learn more about Next.js, you can check out their [documentation](https://nextjs.org/docs).
- Have a basic understanding of [Tailwind CSS](https://tailwindcss.com) (optional)

You can create a free account for Clerk from [the Clerk sign-up page](https://dashboard.clerk.com/sign-up). After creating your account, you'll be redirected to the Clerk dashboard. There, you will be asked to create a new application. Add an application with the name of your choice. This is what the setup for this tutorial looks like:

![Clerk app creation page](./VfxvgIu.png)

After successfully creating the application, you'll be able to visit the application's dashboard:

![Clerk application dashboard](./Y2FoQtw.png)

You can find your API keys in the menu under the **Developers** section. Click on **API Keys** and copy the frontend API key. You'll need this later in the project.

In addition to your Clerk account, Node.js and [npm](https://www.npmjs.com) must be installed on your local computer to create and run the application.

If you want to copy the code and follow along, you can use this [GitHub repo](https://github.com/nemo0/nextjs-clerkdev-custom-profile).

### Creating a Next.js Application

The first step in building this application is to create a Next.js application. To scaffold a Next.js application, run the following command in the terminal:

```bash
npx create-next-app@latest
```

Once the installation is complete, you can run the application using `npm run dev` in the terminal, and the application will start on port `3000`. Next.js will render the `index.jsx` file inside the `pages` folder. You can delete the contents of the `index.jsx` file as it will be customized.

The second step is to integrate Tailwind CSS with your Next.js application. You can follow [this Tailwind CSS installation guide](https://tailwindcss.com/docs/guides/nextjs) to do so.

Then install the [Clerk SDK for the Next.js plug-in](/docs/quickstarts/get-started-with-nextjs). To install the SDK, run the following command in the terminal:

```bash
npm install @clerk/nextjs
```

For using forms effortlessly, you can also integrate the [`react-hook-form`](https://react-hook-form.com) plug-in by running the following command:

```bash
npm install react-hook-form
```

Another plug-in called `react-icons` is used for adding icons to the application. You can install `react-icons` by simply running the following command in your terminal:

```bash
npm install react-icons
```

These previous plug-ins are the only ones that will be used in this application.

## Integrating User Profile in Your Next.js App

To add a user profile to your Next.js app using Clerk, you need to obtain the frontend API key, create a new `.env.local` file, and paste the frontend API key to a variable called `NEXT_PUBLIC_CLERK_FRONTEND_API`. The `.env.local` file should look similar to this:

```bash
NEXT_PUBLIC_CLERK_FRONTEND_API=clerk.noice.bjsdn-81.lcl.dev
```

Then you need to wrap your Next.js application with the `ClerkProvider` component. The `ClerkProvider` wrapper can be found in the `@clerk/nextjs` SDK. The SDK also has methods called `SignedIn`, `SignedOut`, and `RedirectToSignIn`. These components can be used to secure your application. For example, the components wrapped inside the `SignedIn` will require the user to sign in. You can read about the different components [in the official docs](/docs/quickstarts/get-started-with-nextjs).

The `_app.js` file for this application should look like this:

```jsx
import '../styles/globals.css'
import { ClerkProvider, SignedIn, SignedOut, RedirectToSignIn } from '@clerk/nextjs'

import { useRouter } from 'next/router'

import Header from '../components/Header'

const publicPages = []

function MyApp({ Component, pageProps }) {
  const { pathname } = useRouter()
  const isPublicPage = publicPages.includes(pathname)

  return (
    <ClerkProvider frontendApi={process.env.NEXT_PUBLIC_CLERK_FRONTEND_API}>
      {isPublicPage ? (
        <Component {...pageProps} />
      ) : (
        <>
          <SignedIn>
            <Header />
            <Component {...pageProps} />
          </SignedIn>
          <SignedOut>
            <RedirectToSignIn />
          </SignedOut>
        </>
      )}
    </ClerkProvider>
  )
}

export default MyApp
```

You must pass the API key in the `ClerkProvider` through the `frontendApi` prop. The `publicPages` array can store the pages that are available to everyone. But for this article, all the pages will be secured.

The `SignedIn` wrapper holds all the components. That means, if you are signed in, you'll only be able to access the pages. You'll be redirected to the sign-in page if you are not signed in. You'll be redirected to the login screen if you are not logged in using the `RedirectToSignIn` component.

### Header and User Profile

The `Header` component is a very basic header. The code for the `Header` component looks like this in the `Header.jsx` file:

```jsx
import { GiAstronautHelmet } from 'react-icons/gi'
import { CgProfile } from 'react-icons/cg'
import { UserButton } from '@clerk/clerk-react'

import Link from 'next/link'

const Header = (props) => {
  return (
    <div className="w-full bg-purple-600 py-4">
      <div className="mx-auto flex w-10/12 items-center justify-between">
        <Link href={'/'}>
          <a>
            <h4 className="flex items-center text-2xl font-bold text-white">
              <GiAstronautHelmet className="mr-4" />
              Clerk is Awesome
            </h4>
          </a>
        </Link>
        <div>
          <UserButton userProfileUrl="/profile" />
        </div>
      </div>
    </div>
  )
}

export default Header
```

You can see that the `Header` component is using a component called `UserButton`. Clerk provides this component, and the button renders a toggle menu for accessing the user profile:

![UserButton demo](./Fn25xiX.png)

The `userProfileUrl` prop holds the location of the **Manage account** page. Here, the location is `/profile`.

Now, create a new page called `profile.jsx` inside the `pages` folder. You only need to render a single component to generate the user profile:

```jsx
import { UserProfile } from '@clerk/nextjs'

const Profile = () => {
  return <UserProfile />
}
export default Profile
```

The `UserProfile` component provided by Clerk does everything for you and generates an aesthetically pleasing user profile.

If you try to visit the `/profile` route now, you'll need to sign in or create a new account. Clerk already handles the authorization for accessing specific pages. After successfully logging in, you'll be able to visit the user profile page:

![Clerk UserProfile component](./pto9t8C.jpg)

You can also update your profile from here, which you'll learn about in the next section.

### Implementing Custom User Profile

To implement a custom user profile, create a new page called `view.jsx` inside your `pages` directory. This page will render a custom user profile. As this article focuses more on the technicalities of implementing a custom user profile, the design and Tailwind classes will not be discussed.

To help the user access the custom user profile, update your `index.jsx` file like this:

```jsx
import Head from 'next/head'
import styles from '../styles/Home.module.css'

import Link from 'next/dist/client/link'

const Home = () => {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <div className="flex h-screen w-full flex-col items-center justify-center">
        <h1 className="text-6xl font-bold text-purple-600">Clerk is Awesome</h1>
        <Link href={'/view'}>
          <a>
            <button className="mt-4 bg-purple-600 px-4 py-2 font-bold text-white transition-all hover:bg-purple-800">
              View Profile
            </button>
          </a>
        </Link>
      </div>
      <div></div>
    </div>
  )
}

export default Home
```

The previous code shows a centered text, "Clerk is Awesome," and a button for accessing the custom user profile with a link of `/view`.

The final design of the custom profile page will look like this:

![Custom user profile screen](./UXNgz7K.png)

You'll have to use the `useUser` hook available in the Clerk SDK to get the necessary information from the backend. The `useUser` hook returns the values of the current user along with other important information, like the user creation date and external connected accounts if two-factor authentication is connected:

![useUser returned data](./S4YNb0g.jpg)

If you look at the returned data closely, you'll find that the data contains an object `unsafeMetadata`. The `unsafeMetadata` object can hold custom values stored for custom user profile information:

![unsafeMetadata object](./g4Ik4K7.png)

For this article, you can see there are two custom fields: `customBio` and `customName`.

Clerk has three types of metadata for storing additional user information: public, private, and unsafe. Both public and private metadata can be updated or added from the backend, and you can access or view only the public metadata from the frontend. The unsafe metadata can be read or written from the frontend:

![Comparison of metadata types](./WyBBEUz.png)

Because of the ability to write from the frontend, this article will use unsafe metadata for custom user information. You can read more about metadata [in Clerk's documentation](/docs/users/metadata).

Look at the `view.jsx` file:

```jsx
import { useUser } from '@clerk/nextjs'

import Image from 'next/image'

import Link from 'next/link'

const ViewProfile = () => {
  const { isLoaded, isSignedIn, user } = useUser()
  if (!isLoaded || !isSignedIn) {
    return null
  }

  console.log(user)

  return (
    <div className="container mx-auto">
      <div className="flex">
        <div className="mx-4">
          <Image
            src={user.profileImageUrl}
            width={'250px'}
            height={'250px'}
            alt={user.fullName}
            className="rounded-lg"
          />
        </div>
        <div className="ml-4">
          <div className="-mx-4 overflow-x-auto px-4 py-4 sm:-mx-8 sm:px-8">
            <div className="inline-block w-full overflow-hidden rounded-lg shadow-md">
              <table className="w-full leading-normal">
                <tbody>
                  {/* Firstname */}
                  <tr>
                    <td className="whitespace-no-wrap border-b border-gray-200 bg-white px-5 py-5 text-sm text-gray-900">
                      First Name
                    </td>
                    <td className="whitespace-no-wrap border-b border-gray-200 bg-white px-5 py-5 text-sm text-gray-900">
                      {user.firstName}
                    </td>
                  </tr>
                  {/* Last Name */}
                  <tr>
                    <td className="whitespace-no-wrap border-b border-gray-200 bg-white px-5 py-5 text-sm text-gray-900">
                      Last Name
                    </td>
                    <td className="whitespace-no-wrap border-b border-gray-200 bg-white px-5 py-5 text-sm text-gray-900">
                      {user.lastName}
                    </td>
                  </tr>
                  {/* Emails */}
                  <tr>
                    <td className="whitespace-no-wrap border-b border-gray-200 bg-white px-5 py-5 text-sm text-gray-900">
                      Emails
                    </td>
                    <td className="whitespace-no-wrap border-b border-gray-200 bg-white px-5 py-5 text-sm text-gray-900">
                      {user.emailAddresses.map((email) => (
                        <div key={email.emailAddress}>{email.emailAddress}, </div>
                      ))}
                    </td>
                  </tr>
                  {/* Unsafe Metadata Example */}
                  <tr>
                    <td className="whitespace-no-wrap border-b border-gray-200 bg-white px-5 py-5 text-sm text-gray-900">
                      Custom Name
                    </td>
                    <td className="whitespace-no-wrap border-b border-gray-200 bg-white px-5 py-5 text-sm text-gray-900">
                      {user.unsafeMetadata.customName}
                    </td>
                  </tr>
                  <tr>
                    <td className="whitespace-no-wrap border-b border-gray-200 bg-white px-5 py-5 text-sm text-gray-900">
                      Custom Bio
                    </td>
                    <td className="whitespace-no-wrap border-b border-gray-200 bg-white px-5 py-5 text-sm text-gray-900">
                      {user.unsafeMetadata.customBio}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div className="flex justify-center">
            <Link href={'/additional'}>
              <button className="mt-4 bg-purple-600 px-4 py-2 font-bold text-white transition-all hover:bg-purple-800">
                Update Additional Information
              </button>
            </Link>
          </div>
        </div>
      </div>
    </div>
  )
}

export default ViewProfile
```

Don't get overwhelmed. The code can look complicated, but it's not. Now, break down the essential components. Begin by importing the `useUser` hook from the Clerk SDK. Then the `Image` and `Link` components are imported from Next.js.

The `ViewProfile` component renders the user profile. The initial step of using `useUser` is to destructure its essential functions:

```jsx
const { isLoaded, isSignedIn, user } = useUser()
if (!isLoaded || !isSignedIn) {
  return null
}
```

In the previous code, the functions check if the page is not loaded or the user is not signed in. If not, then nothing is rendered. You can console the `user` object here:

```jsx
console.log(user)
```

This will return all the information available to Clerk for the particular user. Now that you have access to the `user` object, you can use it to render the profile values. For example, you can generate the user's profile image by simply accessing the `user.profileImageUrl` key. The first name of the user is stored inside the `user.firstName` key.

The template here only uses these keys: `user.profileImageUrl`, `user.firstName`, `user.lastName`, `user.fullName`, `user.emailAddresses`, and `user.unsafeMetadata`. The custom user profile can be implemented using the `user` object.

### Updating Current User Profile

If you look at the previous code, you'll find that it also contains a link to another page for updating the profile information. Look at how you can edit user information from a custom profile update page.

Create a new page with the name `additional.jsx` file inside the `pages` directory. The `react-hook-form` plug-in will be used here, though it's not necessary for a simple form like this. If your form is large and complex, `react-hook-form` is a great solution. This plug-in makes the binding of the input fields simple. You can look at React Hook Form's "Get Started" [example](https://react-hook-form.com/get-started) to get a basic idea of how it works.

Now take a look at the complete code and then break it into parts:

```jsx
import { useForm } from 'react-hook-form'
import { useUser } from '@clerk/nextjs/dist/client'

import { useRouter } from 'next/router'

const AdditionalUpdate = () => {
  const router = useRouter()

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm()

  const { isLoaded, isSignedIn, user } = useUser()

  const onSubmit = (data) => {
    try {
      user.update({
        firstName: data.firstName,
        lastName: data.lastName,
        unsafeMetadata: {
          customName: data.customName,
          customBio: data.customBio,
        },
      })

      router.push('/view')
    } catch (error) {
      console.log(error)
    }
  }

  if (!isLoaded || !isSignedIn) {
    return null
  }

  return (
    <div className="mx-10">
      <h1 className="py-4 text-2xl font-bold">Update Additional Information</h1>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div>
          <label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="firstName">
            First Name
          </label>
          <input
            defaultValue={user.firstName}
            {...register('firstName', {
              required: true,
            })}
            className="focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
          />
          {errors.firstName && <span className="text-sm text-red-600">This field is required</span>}
        </div>
        <div>
          <label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="lastName">
            Last Name
          </label>
          <input
            defaultValue={user.lastName}
            {...register('lastName', {
              required: true,
            })}
            className="focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
          />
          {errors.lastName && <span className="text-sm text-red-600">This field is required</span>}
        </div>
        <div>
          <label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="customName">
            Custom Name
          </label>
          <input
            defaultValue={user.unsafeMetadata.customName}
            {...register('customName', {
              required: true,
            })}
            className="focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
          />
          {errors.customName && (
            <span className="text-sm text-red-600">This field is required</span>
          )}
        </div>
        <div className="mt-4">
          <label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="customBio">
            Custom Bio
          </label>
          <textarea
            rows={6}
            defaultValue={user.unsafeMetadata.customBio}
            {...register('customBio', {
              required: true,
            })}
            className="focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none"
          ></textarea>
          {errors.customBio && <span className="text-sm text-red-600">This field is required</span>}
        </div>

        <button
          type="submit"
          className="my-4 bg-purple-500 px-8 py-2 text-lg font-semibold text-white transition-all hover:bg-purple-700"
        >
          Update
        </button>
      </form>
    </div>
  )
}

export default AdditionalUpdate
```

The `onSubmit` function is used for saving the updated information to the server. The `user.update` function is used for updating the values. A new object with the updated values is passed into this function:

```jsx
user.update({
  firstName: data.firstName,
  lastName: data.lastName,
  unsafeMetadata: {
    customName: data.customName,
    customBio: data.customBio,
  },
})
```

As you can see from the previous object, the `firstName`, `lastName`, and two custom fields are being updated. The custom fields can be updated by updating the keys inside `unsafeMetadata`.

The `user.update` function is wrapped inside a `try…catch` block. The page will be redirected to the custom user profile if the object is successfully updated.

But how do you render the already existing values of the user? It's implemented using a similar approach to building a custom user profile. The `defaultValue` of the input field is filled with the corresponding `user` object value:

```jsx
<input
  defaultValue={user.firstName}
  {...register('firstName', {
    required: true,
  })}
/>
```

The `register` method is a `react-hook-form` method that registers the input field with the value passed. For example, the previous code registers the value with `firstName`. You can access this value by accessing the `data.firstName` object.

Finally, the complete template is placed inside `form` tags, where the `onSubmit` function looks like this: `onSubmit={handleSubmit(onSubmit)}`. The `handleSubmit` function is a `react-hook-form` function that handles submissions. It takes in another function as a parameter, and the `onSubmit` function is passed here.

The last thing you need to do is add `www.gravatar.com` to your `next.config.js` file. When there is no profile picture set by the user for their profile, a Gravatar is shown. The image component in Next.js requires the hostnames to be added to the `next.config.js`. Your `next.config.js` file should look like this:

```js
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  images: {
    domains: ['images.clerk.com', 'www.gravatar.com'],
  },
}

module.exports = nextConfig
```

Your user profile update page is now ready.

You can access and check the page by visiting the localhost URL, `http://localhost:3000/additional`. You can also check this [GitHub repo](https://github.com/nemo0/nextjs-clerkdev-custom-profile) for all the code from this tutorial.

The functionalities discussed earlier can also be implemented using the Clerk frontend API. The frontend API has endpoints like `https://clerk.example.com/v1/me` for updating the user profile from the frontend. You can check the [frontend API documentation](https://clerk.com/docs/reference/frontend-api) to learn more.

## Conclusion

[Clerk](/) is a great solution for quickly integrating authentication and custom user profiles into your application. It provides more than authentication; you can manage users, sessions, APIs, and more right from the Clerk dashboard.

This article aims to show you how custom user profiles can be built using the Next.js Clerk SDK. You also saw how Clerk components could be used for rapid development.

You can get started with Clerk for free for up to 500 monthly active users in your application. To create a Clerk account, [visit their sign-up page](https://dashboard.clerk.com/sign-up).

---

# Build an App with Clerk, Prisma Cloud, and Next.js
URL: https://clerk.com/blog/build-app-with-clerk-prisma-nextjs.md
Date: 2022-07-27
Category: Guides
Description: Clerk is an easy-to-use, customizable, and secure customer identity platform that provides you with multiple authentication strategies for your application. 

This platform helps developers handle user management processes for their applications, allowing them to avoid re-inventing the wheel in user authentication strategies and focus on developing the core of their business.

[Clerk](/) can be used to add customer identity management to your application and handle authentication for your application by adding custom sign-in methods. It can also help users track the devices signed in to their accounts on the user profile page, and provide leaked passwords protection by comparing the password entered by the user with the passwords found in major data breaches, as well as many more [features](/#home-features).

In this article, you will learn how to build an app using Clerk, [Prisma Cloud](https://cloud.prisma.io), and [Next.js](https://nextjs.org). This will be a simple application that helps you understand how to implement authentication in your Next.js application using Clerk. The finished application will only show the data from the database to the authenticated users.

## The Tech Stack

The following technologies will be used to create the app:

- [Next.js](https://nextjs.org) is a framework built on top of [React](https://reactjs.org). Next.js is optimized for developer experience, and provides all the features required to build powerful and highly interactive applications with no configuration required.

- [Clerk](/) is a customer identity platform compatible with popular stacks such as JavaScript, React, Next.js, Ruby, and Firebase. It allows you to implement a strong authentication system in your application by providing pre-built components such as `<SignIn />`, `<SignUp />`, and `<UserProfile />`. Clerk supports multiple authentication strategies, including passwords, [magic links](/blog/magic-links), social logins, Web3, multifactor authentication and email or SMS passcodes, and allows you to easily implement them in your application.

- [Prisma Cloud](https://cloud.prisma.io) is a cloud-based collaborative environment that provides support to developers using [Prisma](https://www.prisma.io), an object-relational mapper (ORM) that helps you model data in a human-readable format. Prisma Cloud provides you with an online data browser that allows you to easily view and edit data collaboratively online. It also offers a query console and ability to integrate with your Prisma databases and schema.

- [Heroku](https://www.heroku.com) is a cloud platform that allows developers to build, run, and operate applications.

- [PostgreSQL](https://www.postgresql.org) is an advanced open source relational database management system.

## Building an App with Clerk, Prisma Cloud, and Next.js

To follow along in building this app, you need to have the following set up:

- A code editor of your choice
- [Node.js](https://nodejs.org/en/download) and [Yarn](https://classic.yarnpkg.com/lang/en/docs/install) installed on your development machine
- A [Clerk](https://dashboard.clerk.com/sign-up) account
- A [Prisma Cloud](https://cloud.prisma.io) account
- A [Heroku](https://signup.heroku.com) account

You can see all the code for this application in one place in this [GitHub repository](https://github.com/kimanikevin254/clerk-next-prismacloud).

### Creating a Next.js Application

The easiest way to create a Next.js application is by using `create-next-app`, which sets up everything for you automatically. To create the application, run the following command in the terminal:

```bash
yarn create next-app clerk-prisma
```

The command above creates a folder with the name `clerk-prisma`. This application will only contain a navigation bar and a content area. Open `pages/index.js` in the project root folder and replace the existing code with the following:

```js
import styles from '../styles/Home.module.css'

export default function Home() {
  return (
    <div className={styles.container}>
      <nav className={styles.nav}>
        <h2>My Tasks</h2>
      </nav>

      <div>
        <p>Sign in to view your tasks!</p>
      </div>
    </div>
  )
}
```

To provide some styling for the application, open `styles/Home.module.css` and replace the existing code with the following:

```css
.container {
  margin: 1rem auto;
  max-width: 760px;
  text-align: center;
}

.nav {
  background: gray;
  padding: 0.2rem;
}
```

Run the following command in the terminal to start a development server:

```bash
yarn dev
```

Open `http://localhost:3000/` in your browser and you should see the following:

![A website created with Next.js](./TGmz18s.jpeg)

### Adding Clerk

To add Clerk for user authentication in the application, open the [Clerk dashboard](https://dashboard.clerk.com) in your browser and create a new application by providing the required details.

![An image showing the creation of a new app on the Clerk dashboard](./bCq95OT.jpeg)

Provide the application name, and accept the default settings, which will allow the user to sign in using their email address and a password or to use their Google account. Click the **FINISH** button and you will be navigated to your application details page.

> Creating a new application in Clerk automatically creates a new development instance optimized for local application development.

#### Adding Sign-Up and Sign-In Functionality to the Application Using Clerk

In this section, you will add sign-up and sign-in forms, and build a page that is only visible to authenticated users.

Run the following command in your terminal to install Clerk's Next.js SDK, which gives you access to prebuilt components, hooks, and other features provided by Clerk:

```bash
yarn add @clerk/nextjs
```

You now need to link your local development with the Clerk instance created when you initialized your new app in Clerk. On your Clerk dashboard [API Keys page](https://dashboard.clerk.com/last-active?path=api-keys), copy the `Frontend API key`, create a `.env.local` file in the project root folder and paste in the key in the file as shown below:

```env
NEXT_PUBLIC_CLERK_FRONTEND_API={your_frontend_api_key}
```

Open the terminal to kill the running application by pressing `CTRL+C` or `CMD+C`, and relaunch the application with the command below to load the environment variables:

```bash
yarn dev
```

To use the Clerk context in the application, the entire application needs to be wrapped in the `<ClerkProvider />` component. To achieve this, open the `pages/_app.js` file and replace the existing content with the following:

```js
import '../styles/globals.css'
import { ClerkProvider } from '@clerk/nextjs'

function MyApp({ Component, pageProps }) {
  return (
    <ClerkProvider {...pageProps}>
      <Component {...pageProps} />
    </ClerkProvider>
  )
}

export default MyApp
```

It's time to add a sign-in button and some content for authenticated users. You'll achieve this with some pre-built components and a hook provided by Clerk. These are:

- `useUser()`: This is a hook used to access the current user and user state—whether they're logged in or not.
- `<SignInButton />`: This will display a sign-in button on the webpage.
- `<SignUpButton />`: This will display a sign-up button on the webpage.
- `<UserButton />`: This component displays a button for the current user to access their profile details.

You can learn more about Clerk's components, hooks, and helper functions in the [official documentation](/docs/component-reference/overview).

Open `pages/index.js` file and replace it with the following code:

```js
import styles from '../styles/Home.module.css'

import { useUser, UserButton, SignInButton, SignUpButton } from '@clerk/nextjs'

export default function Home() {
  const { isSignedIn, isLoading, user } = useUser()
  return (
    <div className={styles.container}>
      <nav className={styles.nav}>
        <h2>My Tasks</h2>
        {isSignedIn ? (
          <UserButton />
        ) : (
          <div>
            <SignInButton />
            <SignUpButton />
          </div>
        )}
      </nav>

      <div>
        {isLoading ? (
          <></>
        ) : (
          <div>
            {isSignedIn ? (
              <div>
                <p>Welcome {user.firstName}!</p>
              </div>
            ) : (
              <p>Sign in to view your tasks!</p>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
```

Once you've implemented the preceding code, there will be a different view for users who are signed in and users who are not.

Signed Out Users:
![The view for users who have not signed in](./sIsmqeu.jpeg)

Signed In Users:
![The view for users who have signed in](./66NjqYF.jpeg)

### Adding Prisma to the Application

To add Prisma to the application, run the following commands in your terminal:

```bash
yarn add -D prisma

yarn add @prisma/client

npx prisma init
```

The first command installs Prisma as a `dev` dependency and gives you access to the Prisma CLI. The second command installs the Prisma client, which is a query builder, and the last command initializes Prisma in your application. Initializing Prisma creates a `prisma` folder with a `schema.prisma` file. It also creates a `.env` file in the project root folder with the `DATABASE_URL` variable.

To connect to Prisma Cloud, open [https://cloud.prisma.io](https://cloud.prisma.io) in your browser and create a new project. On the "Configure project" page, provide a project name, connect your GitHub account and click the **Create a repository** option. Click **Next** and go to the next page.

![The project configuration page](./ayaapkW.jpeg)

On the "Select template" page, select the **Empty** template option and click **Next**.

![The select template page](./klvxVYV.jpeg)

On the "Configure environment" page, click on **Provision a new database**, select **Heroku PostgreSQL** as the database provider, and click **Sign in with Heroku** to connect your Heroku account. After signing with Heroku, provide a name for your application. Click on the **Create project** button.

![The configure environment page](./j8CclCr.jpeg)

On the "Deploy project page", copy the `DATABASE_URL` and `DATABASE_MIGRATE_URL`, and insert them at the appropriate points in your local `.env` file, then click **DONE**.

![The deploy project page](./8tTSAON.jpeg)

Your local `.env` file should now have the following:

```bash
DATABASE_URL={YOUR_DATABASE_URL_VALUE}

MIGRATE_DATABASE_URL={YOUR_MIGRATE_DATABASE_URL_VALUE}
```

#### Creating a Shadow Database Manually

Some Prisma commands that are used only in development, such as `prisma migrate`, need a temporary second database that is automatically created and deleted every time these commands are run. Because Heroku PostgreSQL is hosted on the cloud, you need to create a shadow database manually and copy the connection string.

While this tutorial will walk you through the relevant steps, if you'd like to learn more about Prisma shadow databases, you can do so [here](https://www.prisma.io/docs/concepts/components/prisma-migrate/shadow-database).

To create the shadow database, open your [Heroku dashboard](https://dashboard.heroku.com/apps), and locate and open the newly created project. Under the **Resources** tab, click on the **Add-ons** search bar and type "Heroku Postgres". Click on the first result to add the database.

![The deploy project page](./8tTSAON.jpeg)

Please note that you will now have two databases, as shown below:

![Two databases on Heroku](./jxDQo5T.jpeg)

Click on the one on top (the one you created manually) to open its details. On the **Settings** tab under **Database Credentials**, click on **View Credentials** and copy the database `URI`. You will add this to your local `.env` file to allow you to connect to the database.

![The shadow DB details page](./V2PggEC.jpeg)

Add the `URI` to the local `.env` file with the key `SHADOW_DATABASE_URL`.

Your local `.env` file should now have the following details:

```env
DATABASE_URL={YOUR DATABASE URL}

MIGRATE_DATABASE_URL={YOUR DATABASE MIGRATE URL}

SHADOW_DATABASE_URL={YOUR SHADOW DATABASE URL}
```

#### Defining a Schema for Your Model

To define a schema for your tasks model, open the `prisma/schema.prisma` file, and replace the existing content with the following:

```prisma
datasource db {
  provider = "postgres"
  url      = env("MIGRATE_DATABASE_URL")
  shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
  referentialIntegrity = "prisma"
}

generator client {
  provider = "prisma-client-js"
  previewFeatures = ["referentialIntegrity"]
}

model Tasks {
  id  String  @id @default(cuid())
  task String
}
```

The `datasource db` provides details for connecting to the database for running migrations and querying. When querying the database after running the migrations, the value for `url` in `database db` will be switched to `env("DATABASE_URL")`. This is because at the time of writing, one of the limitations of the data proxy is that it can only used to [query the database with Prisma Client](https://www.prisma.io/docs/data-platform/data-proxy#important-considerations-about-the-data-proxy). The `DATABASE_MIGRATE_URL` contains a direct connection string to the database that will be used to run migrations.

The tasks model will only contain two fields:

- **`id`:** The task id
- **`task`:** The task name

#### Running the Migrations and Adding Some Data with Prisma

To run the migrations and add the `tasks` table to the database, run the following command in your terminal, and provide a name for the new migration:

```bash
npx prisma migrate dev
```

When the migration runs successfully, you should see this message on the terminal:

![A successful prisma migration](./CwMw0jY.jpeg)

Now that your database is in sync with your schema, you can add some data with Prisma. To do this, run the following command in your terminal to open Prisma Studio in your browser:

```bash
npx prisma studio
```

After Prisma Studio loads, select your model to add some data. Click on the **Add record** button, add three tasks, and click on the **Save 3 changes** button to save the tasks.

![Prisma Studio interface](./8ce8zc6.jpeg)

#### Showing the Data to Authenticated Users

Open the `prisma/schema.prisma` file and change the `url` value in the `datasource db` to `env("DATABASE_URL")`. The `prisma/schema.prisma` file should now look like this:

```prisma
datasource db {
  provider = "postgres"
  url      = env("DATABASE_URL")
  shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
  referentialIntegrity = "prisma"
}

generator client {
  provider = "prisma-client-js"
  previewFeatures = ["referentialIntegrity"]
}

model Tasks {
  id  String  @id @default(cuid())
  task String
}
```

Next, you need to fetch the data from the database. This can be achieved by modifying the `pages/index.js` file as shown below:

```js
import styles from '../styles/Home.module.css'

import { useUser, UserButton, SignInButton, SignUpButton } from '@clerk/nextjs'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

export default function Home({ tasks }) {
  const { isSignedIn, isLoading, user } = useUser()
  return (
    <div className={styles.container}>
      <nav className={styles.nav}>
        <h2>My Tasks</h2>
        {isSignedIn ? (
          <UserButton />
        ) : (
          <div>
            <SignInButton />
            <SignUpButton />
          </div>
        )}
      </nav>

      <div>
        {isLoading ? (
          <></>
        ) : (
          <div>
            {isSignedIn ? (
              <div>
                <p>Welcome {user.firstName}!</p>
                {tasks ? tasks.map((task) => <p>{task.task}</p>) : <div></div>}
              </div>
            ) : (
              <p>Sign in to view your tasks!</p>
            )}
          </div>
        )}
      </div>
    </div>
  )
}

export async function getServerSideProps() {
  const tasks = await prisma.tasks.findMany()
  return {
    props: {
      tasks: tasks,
    },
  }
}
```

Open `http://localhost:3000/` in your browser, and once you've logged in, you should be able to see the tasks you just added.

![The added tasks after logging in](./NTxO8tD.jpeg)

## Conclusion

In this article, you have learned about [Clerk](/), a powerful service that can handle user identity management for you. You have also learned about the various use cases of Clerk, a few of its components and hooks, and how you can [integrate it into your Next.js application](/nextjs-authentication) to easily handle user authentication. Finally, you have learned how to integrate Prisma into the application, use Prisma Cloud, and add data to your cloud-hosted database on Heroku.

---

# The Journey to Modern Web Authentication
URL: https://clerk.com/blog/the-journey-to-modern-web-authentication.md
Date: 2022-07-21
Category: Company
Description: A blog post about the story of Clerk; our journey of bringing seamless authentication to the Modern Web, where we stand now, and what lies ahead.

Web authentication is an acronym and protocol ensemble ([SSO](https://en.wikipedia.org/wiki/Single_sign-on), [OAuth](https://oauth.net), [SAML](https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language), [OpenID](https://openid.net/connect), [SCIM](https://en.wikipedia.org/wiki/System_for_Cross-domain_Identity_Management), [FIDO](https://en.wikipedia.org/wiki/FIDO_Alliance), [PKCE](https://oauth.net/2/pkce), [JWT](https://jwt.io), etc...) that traditional user management software implements one way or another. Developers know that adding authentication to an application is a mundane and tedious task and they increasingly choose to outsource it.

Authentication requires user input, usually collected via redirection to authentication pages such as the sign-up or sign-in page. UX-wise the redirection is a clean cut. Things get fascinating in the modern web world with [React](https://reactjs.org), [Vue](https://vuejs.org), [Svelte](https://svelte.dev) or [Angular](https://angular.io) applications. Users expect to land and stay on the same tab, sign in fast and securely with a Google-like experience, and maintain their sessions in a safe and unobtrusive way until they log out.

Let's mull over how to build a sign-in form with SMS [two-factor authentication](https://en.wikipedia.org/wiki/Multi-factor_authentication) (2FA) in React. Where will the state live? Will the sign-in flow be bookmarkable? How will we transform user credentials into a session? Should I use a session cookie or a JWT? How will I ensure that the UI doesn't flicker when a guest user authenticates?

User management software so far offers the necessary authentication features but integrating them into your React application is cumbersome. This is why we've built [Clerk](/); to offer a modern-web customer identity platform that just works.

From early on, our goal was to focus on developer experience. To achieve that we had to start with a framework so we picked the most popular at the time, [Next.js](/docs/quickstarts/get-started-with-nextjs). We knew that React users expect components and hooks, so we offered both of them from the start.

While building our [React components library](/docs/component-reference/overview), we had to decide how we will package it in order to make it easy to set up and upgrade. Hot-loading the latest version using semantic versioning was our preferred choice. Another requirement was the ability to customize our components to match the look'n'feel of the host application. We decided to start simple with CSS overwrites.

The hooks API design was also exciting. We debated a lot whether *`const {user} = useUser()`* should return *`null`* or an empty *`new User()`* when not authenticated. We spent countless hours trying to figure out how should we store and update the session state. The first iteration resulted in a polling mechanism with a lot of auth data piggybacking.

The initial adoption was really warm. Clerk began to mature. We started designing new components, adding more authentication features, revamping our state management, and improving our developer experience.

In the meantime, modern web frameworks were evolving rapidly. [SSR](https://nextjs.org/docs/basic-features/pages#server-side-rendering), used mostly for public, static content back in 2020 became the defacto choice for SaaS. Edge computing support for fast API endpoints was added and distributed web infra­structure improved immensely. So we followed. Clerk was ahead of the game and one of the first solutions to add native SSR support for our [hooks](/docs/reference/overview). We also moved to [session validation at the Edge](/docs/request-authentication/nextjs#using-edge-middleware) so that verifying the JWT takes less than 1 ms.

In the first half of 2022, the product went from strength to strength. We added [organizations](/docs/organizations/overview), we bridged [web3 and web2 authentication](/blog/introducing-web3-authentication), we integrated with JWT-powered databases and tools such as [Hasura](/docs/integration/hasura) and [Supabase](/docs/integration/supabase), we expanded to more React frameworks such as [Remix](/docs/quickstarts/get-started-with-remix), [Redwood.js](/docs/quickstarts/get-started-with-redwoodjs), [Gatsby](/docs/quickstarts/get-started-with-gatsby), [Expo](/docs/reference/clerk-expo), and we've just released our new, fresh, and [fully customizable ClerkJS Components](/blog/changelog-2022-07-15).

For the second half of the year, we have a lot of exciting epics in the pipeline. First and foremost, we aim to be the first authentication solution that works with [React server components](https://nextjs.org/docs/app/building-your-application/rendering/server-components). In addition, customers request [SSR for our ClerkJS Components](https://github.com/clerkinc/javascript/discussions/183). Remember how hot-loading was a great idea two years ago? With strong SSR support, it's not anymore. We have also started working on making all our [SDKs isomorphic](https://github.com/clerkinc/javascript/issues/127) to seamlessly work on Node and V8 runtimes. And of course, we will expand our customization capabilities, as we intend to allow developers to use their [Chakra](https://chakra-ui.com) or [Material UI](https://mui.com) components in their Clerk authentication forms.

On a personal level, I am looking forward to seeing how bleeding-edge web tech will evolve and shape how we build applications. If you are intrigued by any of these topics, [talk to us on Discord](https://clerk.com/contact/support) or [apply](/careers) to join our expanding team. We are an international, all-remote team and we are [currently hiring](/careers).

---

# What is Next.js?
URL: https://clerk.com/blog/what-is-nextjs.md
Date: 2022-07-20
Category: Insights
Description: Next.js is a framework in the React ecosystem that is primarily used for developing JavaScript applications. Understand the ins and outs below.

*Updated: 09/01/2022*

Web applications are a fundamental part of the modern internet. As a web developer, you likely spend a lot of time trying to make the development process for these apps simpler and more efficient. That's why you should understand how Next.js works.

Next.js is a popular framework that makes it easier to develop JavaScript applications of all kinds. In this guide, you'll learn the answers to questions like, "What is Next.js?" and, "Why use Next.js?" You’ll also learn about the best use cases for Next.js in your development process. If you're ready to learn more, then let's dive in.

## **What Is Next.js?**

Next.js is a React framework that gives programmers a structured environment to quickly create fast web applications. With Next.js, you can use React’s powerful tools without having to build your application from the ground up.

React is a specific JavaScript library designed to help you develop interactive user interfaces (UIs). On its own, React is a useful tool, but it still requires a significant amount of work to use it correctly. That's why Next.js was built. But how does Next.js work?

Next.js is a React framework. The difference between libraries and frameworks is important. Libraries are just collections of useful tools. Like with a brick-and-mortar library, you're responsible for finding the specific information and tools you need. You have to call the library and tell it what you need.

In contrast, frameworks handle that for you. When you work within a framework, you don't need to worry about calling the library or pulling the tools. It acts as a frame for your application, giving it a fundamental structure and preventing errors from creeping in.

That's what Next.js does for React. The Next.js framework structures the React library and gives it a solid form. When you start a project using Next.js, the framework configures many settings behind the scenes and provides extra commands that allow you to accomplish tasks that aren't possible through the React library alone. Because of that, building applications within the Next.js framework takes less time while still offering all the benefits of the React library.

## **What Functionalities Does Next.js Offer?**

Next.js offers a broad range of functionalities. The framework was designed to provide not only structured access to the React library but also extra features. When you choose to use Next.js to build an application, you're guaranteeing that you'll have access to these functionalities.

### **Client-Side Rendering for Interactivity**

One of the most valuable tools Next.js offers is client-side rendering. There are three ways that Next.js can render a user interface: client-side, server-side, or static site generation. Client-side rendering is the best way to make an interactive, responsive UI.

With client-side rendering, the UI is generated on the client's end of the application. The server sends basic HTML to the app along with JavaScript code. That JavaScript code contains the instructions for the app to generate the UI, including more complex HTML, in the moment.

This allows the connection between the client's device and the server to happen quickly. All of the complicated parts of the rendering the UI happen on the client's end. As a result, there's no need to constantly query the server regarding how the UI should change based on the client's actions. The UI is able to react to the client instantly, making interactive elements smoother and less prone to delays.

### **Static Site Generation to Help Automate Your Process**

If interactivity isn't a primary goal of the application, then Next.js also supports static site generation. With this method, the user interface is prerendered by the server. More importantly, the server needs to generate this only once. The HTML is created and then stored in a content delivery network (CDN). Whenever that specific UI is needed, the app pulls the HTML from the CDN and presents it. There's no need for any rendering in the moment for the client or the server.

Prerendering your UI with Next.js's static site generation is a great way to automate certain parts of your process. Static pages may not be the most interactive, but they're quick to load and require no work from your own servers. This method takes some pressure off your servers and allows you to automate routine tasks like displaying loading screens, menus, and other low-interaction pages.

### **Ability to Build Complete Web Applications Quickly**

Part of what makes working in any framework so appealing is the way it can speed up application development. When you work with Next.js, you don't need to build your app from scratch. The framework has already laid the foundation and set the parameters for you. It even has rules and guidelines in place to help you avoid making mistakes that could cause delays or failures.

That functionality makes it easy to build your next web application quickly. Next.js helps you avoid wasting time on basic tasks and setup. Instead, you can start working on the meat of your application right away, building a complete, functional, good-looking app in less time.

## **The Impact Next.js Has on the User Experience**

It's clear that Next.js offers developers many potential tools to make applications faster and more efficient. However, the framework also impacts the user experience (UX). Next.js provides flexibility and customization options that make the UX better in three important ways:

- Security
- Speed
- Personalization

Here's how the Next.js framework supports each of these UX elements.

### **Lack of Direct Database Connection, Keeping Static Websites Secure**

Application security is a fundamental necessity for modern developers. If you don't create a secure app, your users are at risk of having their devices hacked and their information stolen. Obviously, this has a significant negative impact on the user experience.

Next.js can help make your apps more secure, particularly if you use static site generation. With static generation, there's no direct connection to any databases. User devices query the CDN instead, which provides the prerendered code. As a result, there's no easy way for hackers to inject malicious code into the database results. Users face a lower risk of malware because Next.js has stripped the need to render code on either end of the process.

Furthermore, static site generation protects user information on your servers, too. Hackers who access your web application won't be able to study its direct connection to your servers because there isn't one. There's no way for them to learn how to call your server databases and potentially access sensitive information like sign-in details or payment information.

### **Significantly Faster Page Load Times**

Whether you choose static site generation or client-side rendering, Next.js can help you significantly reduce page load times.[ According to Google](https://www.thinkwithgoogle.com/marketing-strategies/app-and-mobile/page-load-time-statistics), visitors are 32% more likely to leave a webpage that takes three seconds to load compared to a page that loads in one second. Reducing page load times is a simple but valuable way to keep users engaged with your site and prevent bounces.

Static site generation means that there's no need to render a page at all. Next.js allows the next page to load significantly faster because all it needs is the HTML that the CDN provides. There's no additional rendering requirement on either end.

Client-side rendering can be almost as fast. There's no extra delay between your server and the client's device, since your server is just providing HTML and JavaScript instructions. The client's device is responsible for rendering the actual user interface. As long as the device has reasonable rendering times, the user will see the entire page significantly faster than other methods allow.

### **Ability to Create a Completely Customized Front End**

After security and speed, the third element of a great user experience is a beautiful, functional user interface. Next.js gives UX teams the ability to build a completely customized front end to fit the app's brand and target audience.

Some frameworks limit what developers can do with various elements. That's the nature of a framework: While it offers support, it also imposes limitations, just like walls in a house. However, Next.js has been carefully constructed to give developers complete freedom to customize the front end of their web applications.

That freedom means it's easy to develop appealing front-end UIs that users enjoy interacting with. There are no clunky requirements that may get in the way of your dev team's goals or needs. You can focus on providing a great experience for your users instead of fighting with the framework or reinventing the wheel.

## **Why Front-End Developers Use Next.js**

You might still be wondering, "Why use Next.js?" It might help to understand its appeal to front-end developers. Devs using the framework appreciate it for the following functionalities.

### **Server-Side Rendering**

Server-side rendering allows your web application to quickly display interactive pages that may not be easy to render on client devices. This tool lets you implement more complicated user interfaces by placing the load on your servers instead of the client's device.

Your server will generate the HTML for each request, along with JavaScript instructions for interactivity. The HTML will allow the page to quickly display a noninteractive page. After that's displayed, the JavaScript instructions will be interpreted behind the scenes to make the page interactive. In most cases, users won't notice the delay between the page appearing and the JavaScript making it functional, since they need time to decide what to click next. Meanwhile, you get to develop more complex interactive pages without risking slowing down your site.

### **Automatic Compilation and Bundling**

A significant benefit of using a good framework like Next.js is the way it takes basic tasks off your plate. Next.js is structured to provide automatic compilation and bundling, meaning that it's "zero config." You don't need to do any configuration to get the framework ready for production.

Without the need to configure anything, Next.js is perfectly optimized for production from the moment you start development. That can save you significant time and prevent annoying and wasteful compilation failures. When your application is finished, all you need to do is test the compilation and bundling process once, and then move it to production. You can trust Next.js to handle the rest.

### **Importing CSS Files**

Next.js allows you to directly import CSS files from a JavaScript file. The built-in CSS parser makes it easy to import global style sheets that will apply to the entire web application. The style sheet will ensure that every part of your app is presented consistently, so you don't need to set the presentation for each element individually.

If you do have specific components that need unique CSS, that's possible too. You can import CSS Module files anywhere in an application just as easily as you would apply a global style sheet. The module will override the global style sheet in the locations you apply it to, so you can customize specific elements with ease.

This is possible because Next.js extends the import function to cover more than just JavaScript. If you choose to use the framework, this extended import functionality makes rapid development simpler and more accessible.

### **Data Fetching**

Next.js data fetching includes server-side rendering, client-side rendering, and static page generation. You're not limited to just one of these methods, either. While you can develop your entire application with one data-fetching technique, you can also combine them so each page of your site is generated as efficiently as possible.

For instance, you could use static generation to automate your simplest pages, such as news articles or blog posts. Meanwhile, you could use server-side generation to load your homepage, where things may frequently change but speed is of the essence. Finally, if you have a ticker page or other pages that should update without a refresh, client-side rendering is ideal. Next.js allows you to choose which pages are loaded with which method, giving you more flexibility.

### **Code Splitting**

Web applications rely on code splitting to function. Most web applications involve multiple pages, each of which can be visited through a specific URL. That makes every page a unique entry point to the app.

Code splitting is the process of dividing the total application's code bundle into chunks that are relevant to each page in particular. This speeds up load times by avoiding the need to render code that's irrelevant to the specific page.

Next.js automatically handles code splitting for you. The framework takes each file in the "pages/" directory and generates a specific JavaScript bundle for it, which will be called up when visitors access the page. This saves you time and effort.

### **React Ecosystem Access**

Finally, Next.js gives you access to the entire React ecosystem. As a React framework, it's built to cooperate with other React components. You can use all of the features the React library offers, taking advantage of a broad range of tools to make your UI more appealing.

## **When Should You Use Next.js for Development?**

If you're still not sure about whether Next.js is right for your application, it might help to understand the situations in which the framework really shines. Some of the best opportunities to use Next.js include the following.

### **Building SaaS Products**

If you have a software-as-a-service (SaaS) product that you want to expand, time is of the essence. Both development time and page load times are essential factors when you're trying to make your SaaS product more appealing. Next.js helps you trim the time wasted on both of these issues.

You can use Next.js to build out new SaaS features and products in less time. The framework will help you move from idea to finished product without having to waste time on configuration and bundling. Meanwhile, the data -fetching options allow you to build an application that loads faster on every page.

### **Building Web Applications and Portals**

Similarly, Next.js is a great way to build new web applications and portals. Paired with the right [Next.js authentication solution](/nextjs-authentication), the static site generation feature helps you build fast-loading pages that allow your users to quickly sign into the app or portal. You can even implement [multifactor authentication](/blog/nextjs-supabase-todos-with-multifactor-authentication) in your portal to strengthen your security and protect your users' data.

### **Creating an Interactive User Experience**

Next.js is structured to make interactivity a priority for the user interface. Whether you use server-side or client-side rendering, you can produce highly interactive webpages that load in less time. Each page can be built with the rendering method that allows for the most efficient interaction.

Furthermore, the ability to customize your front end makes Next.js a valuable tool for developing a unique UI that's interactive in the ways you need. You're not stuck trying to build an application around the framework's assumptions. The result is a front-end UX that's ideal for any interactive application.

## **How You Can Incorporate Next.js Into Your Development Environment**

If you're interested in using Next.js in your development environment, Clerk can help. [Clerk offers the easiest solution for Next.js authentication](/nextjs-authentication) on the market. Learn more about how you can keep your Next.js application secure and accelerate your development with Clerk's Next.js authentication tool today.

---

# Clerk joins the Netlify Jamstack Innovation Fund
URL: https://clerk.com/blog/clerk-joins-netlify-jamstack-innovation-fund.md
Date: 2022-07-12
Category: Company
Description: Clerk powers authentication for over 5,000 Jamstack teams – now we're working with Netlify to further our commitment to the ecosystem

Clerk provides serverless, edge-compatible authentication to over 5,000 Jamstack teams. Today, we're thrilled to join the Netlify [Jamstack Innovation Fund](https://www.netlify.com/jamstack-fund) to further our commitment to the ecosystem.

Netlify has been an inspiration for Clerk since their co-founder, Matt Biilman, [spoke about Jamstack in 2016](https://vimeo.com/163522126). The idea felt like it would change the way we build software, *and indeed it has*.

Clerk leverages Jamstack to set a new standard for developer tools. Instead of only providing a backend SDK, we also offer a frontend SDK with React components and hooks to empower frontend developers.

For example, our [`<SignUp/>` component](/components/sign-up) embeds a complete, conversion-optimized sign-up flow in our customer's application:

![Clerk Joins Netlify Jamstack Innovation Fund guide illustration](./9507286557ea85867e815093a4f0108edfa4cdf8-720x486.svg)

And for complete customization, frontend developers can instead leverage our [`useSignUp()`](/docs/reference/clerk-react/usesignup) hook to build a UI of their own.

Both `<SignUp/>` and `useSignUp()` are implemented entirely on the frontend, while Clerk's API is responsible for the backend of user and session management. This enables teams to build fully-featured authentication in minutes instead of days or weeks.

We're proud to be recognized as one of the 10 most promising Jamstack startups, and excited for the future as we begin working closely with the Netlify team. Stay tuned!

---

# Authentication vs. Authorization: What's the Difference?
URL: https://clerk.com/blog/authentication-vs-authorization.md
Date: 2022-07-06
Category: Insights
Description: Understand the differences between authentication vs. authorization and the purpose they both serve.

Authentication and authorization are essential parts of security. Companies need both to protect their networks and systems from unauthorized access to business resources. Let’s look at the core elements of authentication vs. authorization and ways to leverage them to enhance your organization’s security posture. The evolution of network security makes access control more critical than ever. While people tend to use the terms *authentication* and *authorization* interchangeably, it’s important to understand how they contrast and how each helps protect company applications.

## **The Differences Between Authentication vs. Authorization Explained**

Below is an overview of the differences in how each process works.

### **The Authentication Process**

[Authentication](/features/web3) focuses on recognizing and proving that an individual is using the correct identity. For example, when someone logs into their workstation, they’re prompted for verification through credentials like a username or password.

An authentication solution running behind the scenes checks the information provided against a database of stored credentials. If the data checks out, the user gains access to the target resource.

Usernames and passwords have been the go-to for most businesses when asking workers to verify their identity. Security protocols typically require employees to keep their passwords secret to prevent unauthorized users from using their credentials in a way that could harm the company.

As hackers have evolved the methods they use to go after companies’ systems, passwords have become more vulnerable. Many IT departments try to keep passwords secure by requiring users to enact a certain degree of complexity when creating them. In addition, workers are prompted by the system to change their passwords frequently, usually every 30 days.

The onus is on IT personnel to manage stored complex passwords. The difficulty of remembering intricate passwords often leads users to reuse their passwords on multiple devices and in different systems. Even if a password meets the length requirements, the actual entry phrase may be extremely uncomplicated, making it easy for cybercriminals to guess the pattern and gain system access using stolen credentials.

### **The Authorization Process**

Authorization covers the permissions provided to users when it comes to system resources. For example, someone working in the accounting department may have permission to access accounting software that isn’t granted to someone who works in operations.

However, having permission to access that application doesn’t mean the user has free rein to go where they want. While they may have permission to log certain transactions, the worker may be blocked from functions that allow them to retrieve sensitive information like Social Security numbers and bank account information.

Additional privileges are typically granted based on a user’s role within a company. For example, an IT director would likely have system permissions that aren’t given to an application developer. At the same time, that IT director would likely not have access to the repository where software engineers store their code.

System administrators usually control who receives privileges to access various organizational resources and how far those permissions extend. Authorization is about making sure individuals receive the permissions they need and ensuring they don’t proceed beyond those set boundaries.

Let’s use a nightclub analogy to wrap up the contrast between authentication and authorization. Authentication is what gets you past the line and through the doors. However, that doesn’t mean you get to go right up to the VIP lounge. Instead, someone must give you specific permission to access that area.

## **Types of Authentication**

Let’s look at the different methods employed by businesses to validate a user's identity.

### **Multifactor Authentication**

Passwords don’t offer the level of security that’s necessary in today’s digital world. Cyberthieves use methods like keyloggers to capture password entries or look for clues to a person’s work credentials by poring over their social media profile. Some resort to using password-cracking tools, which try out various username-and-password combinations until they get a hit.

[Multifactor authentication](/features/multifactor-authentication) (MFA) adds an extra layer of security to identify users. That way, hackers need more than a user’s password to get past a company’s security. Users must identify themselves in multiple ways, reducing the risk of hackers using employee information to steal data or sabotage business systems.

### **Two-Factor Authentication**

Two-factor authentication (2FA) requires users to provide two authentication factors before receiving access to a system, application, or device. It provides more robust security protections than requiring only a password or code.

Most 2FA methods require users to provide a password and then a security token or one-time password (OTP) that is generated from a separate device, like a mobile phone. The extra layer of security makes it more difficult for attackers to use a password to access a user’s device or get into their online accounts.

### **Single-Factor Authentication**

Single-factor authentication (SFA) grants access to a system by asking a user for only one type of identification. Password-based SFA is the most common type used by organizations. The best way to implement SFA is by establishing robust password protocols that are enforced by system administrators.

The drawback to SFA is that many users have difficulty coming up with strong passwords that they can easily remember. Problems also result when IT departments don’t enforce standards that ensure users don’t try to get around the protocols by repeating passwords or using patterns that are easy for an experienced hacker to figure out.

### **Token Authentication**

Tokens are a form of 2FA that uses digitally encoded signatures to authenticate a user attempting to access a network or another IT resource. The token comes in the form of a unique OTP that's generated every time a user logs into a system. Users enter the information along with another authentication factor to prove their identity.

Many organizations use security tokens because it’s easy to scale the system to accommodate new employees. It’s also possible to use access tokens on multiple servers. The flexibility of the process allows companies to use security tokens for various applications and websites simultaneously.

**Biometric Authentication**

Biometric authentication uses distinct biological characteristics to verify someone’s identity. Using your fingerprint to log into your phone is a form of biometric authentication. The physical trait used to identify a person must match information that was previously stored in a biometric authentication system.

Other standard biological information used for this method of authentication include:

- Genetic material, like DNA
- Iris recognition
- Retinal scans that analyze the blood vessels at the back of the eyes
- Hand geometry recognition, which evaluates the unique characteristics of a person’s hand
- Voice identification

Biometric devices consist of a scanner, technology that converts and evaluates biometric data for comparison, and a database that stores biometric information. The device used for scanning can include a fingerprint reader or voice analyzer. Once the user provides their data, the biometric application attempts to match it to a previously stored sample.

## **How to Choose an Authentication Strategy**

Most modern companies have developers located everywhere, making it more complicated to implement effective security measures. Establishing an authentication strategy goes a long way toward striking a balance between continued flexibility for employees and protecting business assets.

### **Evaluate Your Environment**

Look at your company's available hardware to determine whether it’s sufficient to support multiple login and authentication requests. You don’t want to end up with a bunch of authentication failures that keep workers from performing their jobs. Review the network connectivity available and make sure remote users have what they need to establish connections.

### **Establish a Strong Password Policy**

If passwords are going to be part of your security posture, you need to establish strong policies governing their use. First, encrypt any passwords that are sent over the network to prevent them from getting intercepted. You want to make it difficult for attackers to crack user credentials. Ideally, the password should change by the time the attacker figures things out.

Passwords should be easily remembered by individual users but complex enough to ward off potential hackers. While characters like hashtags and “at” symbols can aid in that effort, adding too many of them can make it harder for users to remember. Users can add a unique suffix to a password, like [dandelion@hardtoguess.net](mailto:dandelion@hardtoguess.net), to make it more complicated. Other rules your organization should follow when it comes to password creation include:

- Not using any part of the user’s name
- Making the password at least eight characters in length
- Having the password contain at least one non alphabetic character
- Adding both upper- and lower-case characters
- Prompting users to change passwords at least every 45 days, though 30 is ideal

Make sure to limit how many times users can try logging in with an incorrect password before a lockout policy is implemented. Many hackers use tools that endlessly guess at password options. However, be aware that hackers can take advantage of such a policy to launch a denial-of-service (DoS) attack that locks out legitimate users. If employees forget their password, set up options that allow them to recover their account securely.

### **Consider Multifactor Authentication**

Adding MFA to your organization’s security posture provides extra layers of protection around employees' credentials and sensitive data. If you work in certain industries, like finance, MFA may be required to comply with established regulations.

The noninvasive nature of MFA doesn’t interfere with your IT infrastructure. Many MFA solutions on the market allow companies to enable single sign-on (SSO) for all company platforms, meaning users don’t have to keep up with complicated passwords for every application.

MFA offers additional security for remote workers, whom hackers often target. Requiring a second confirmation of identity alleviates concerns around cyberthieves using compromised credentials to log into company devices or systems.

## **Types of Authorization**

Organizations should establish access boundaries for users, software applications, and even specific hardware using company resources. The two main methods of granting authorization to users are role-based access control (RBAC) and attribute-based access control (ABAC).

### **RBAC**

RBAC helps organizations maintain control over authenticating users while authorizing them to access systems and applications. It focuses on providing rights to individuals based on their role, the environment in which they work, and specific resource attributes. RBAC controls broad access granted to users throughout an organization.

Administrators manage the distribution of permissions to various organizational roles and the users assigned to those groups. Certain users may be assigned to a group that lets them edit sensitive information while individuals in a different category receive view-only permission.

Some users may be eligible for assignment to multiple role groups that expand their access within an organization. A project manager may have more permissions granted to them via several groups while an analyst working under them would receive more limited access.

The most significant benefit of using RBAC for authorization is that administrators don’t have to make major changes whenever someone switches jobs or leaves the company. Instead, the administrator removes that individual from a role group and moves them to a new one. RBAC also makes it easier to grant necessary permissions to new employees based on their roles.

### **ABAC**

ABAC, also called policy-based access control (PBAC), is often put in place to protect information held in databases, business applications, application programming interfaces, and microservices contained within complicated architectures. Users receive permission to access system resources based on attributes like their role, the device being used, the attempted action, or their location. Each ABAC attribute must align with an established policy before the user receives access to the desired resource.

Organizations typically use ABAC when there’s a need to set up more dynamic security parameters versus those available through RBAC. The granular detail makes it possible for businesses to meet unique security challenges.

Policies for ABAC fall under the governance of corporate policies. Any changes made are enforced throughout the entire company. It’s also easier to implement complicated regulatory requirements with ABAC. Administrators gain real-time control over users' attempts to access company assets, systems, and networks.

ABAC makes it possible to manage a larger pool of control factors versus RBAC. It reduces the risk of users managing to gain unauthorized access thanks to the level of control it offers. For example, someone who works in finance could be restricted from accessing certain bank information outside of specific time periods or particular locations.

## **Authorization and Its Relation to User Permissions**

Authentication is about establishing the identity of an entity trying to gain access to assets, networks, systems, or data controlled by an organization. That includes verifying the host ID of a remote machine, validating the certificate of a software component, or checking an employee's credentials through various means.

Once that entity gains access, the authorization process kicks in to determine what permissions are available. That includes looking at the role groups that entity belongs to and what access they have in different systems and applications.

## **How Authorization and Authentication Relate to Identity and Access Management**

Identity management involves making sure that users have the access they need for various IT resources. It ties directly into the process of authenticating users and access management, controlling where users are allowed to go and what actions they can take with granted permissions.

One benefit of identity and access management is that organizations can ensure that users don’t have more access than necessary. That helps thwart attackers hoping to use stolen credentials to access company data and networks.

## **How to Determine Which Method of Authentication Is for You**

Network security aims to ensure authorized individuals have required access while keeping out unauthorized users. Setting up ABAC properly can quickly devolve into complexity. If there are no strict regulatory guidelines for your industry, then RBAC may be sufficient for your organizational needs. There are also additional costs and human resources required to implement ABAC.

Regardless of which method you choose, try to apply the minimum number of filters that are necessary to comply with your company's security posture. Plan out directory data and the approaches your business wishes to take in granting access.

It’s also possible to use RBAC and ABAC in a hierarchical manner, through which RBAC covers broader protocols and ABAC kicks in when there’s a need for finite security management. An example of that would be using RBAC to figure out which groups within an organization are allowed to access a resource. The company could then use ABAC to figure out the permissions given to users and any actions they can take.

## **How You Can Utilize Authentication Concepts and Authorization Methods**

Authorization policies manage access to IT resources and control what users do with that permission. If you are going to make passwords part of your company’s access protocols, make sure you implement strong password policies to prevent employees from using combinations that could make it easy to compromise their credentials.

One way for companies to expand their security protections is by implementing MFA in addition to using IDs and passwords. Having a secondary method for user authentication keeps hackers from using stolen information to access company resources.

When deciding between RBAC and ABAC, go with the option that covers your essential security needs without adding unnecessary complexity. You can also choose to combine the two to ensure that you’ve established the most robust security protection possible for your organization.

Ready to start your authentication journey? [Start building your authentication journey for free with Clerk](https://dashboard.clerk.com/sign-up).

---

# Refactoring Stripe's API for frontend access
URL: https://clerk.com/blog/refactoring-stripes-api-for-frontend-access.md
Date: 2022-06-10
Category: Engineering
Description: We built `use-stripe-subscription` to make it easier for React developers to implement Stripe Billing

Today we launched [`use-stripe-subscription`](https://github.com/clerkinc/use-stripe-subscription), a package that makes it easier for frontend developers to implement Stripe billing. It features:

- `useSubscription()` - a React hook that returns:
  - `products` - an array of Product objects available for subscription
  - `redirectToCheckout()` - Redirects to Stripe Checkout to purchase a subscription to one of the `products`
  - `subscription` - the current customer’s active Subscription object, if it exists
  - `redirectToCustomerPortal()` - Redirects to Stripe Billing’s Customer Portal so the customer can manage their subscription
- `<Gate>` - a component that selectively renders children based on the customer’s subscription

`use-stripe-subscription` is open-source and was built to work with any authentication and user management solution, not just Clerk.

## Why did Clerk build this?

Clerk is a Customer Identity *Platform.* We don’t just handle authentication, we also make it easier to sync and leverage customer identity with developers’ favorite tools.

`use-stripe-subscription` leverages customer identity to add a new authorization layer to Stripe’s API. By default, Stripe’s API is only designed for backend access, since it relies on a secret key for authorization that cannot be exposed to the frontend.

We added a per-customer authorization layer, which allows frontend developers to securely retrieve subscription information about the signed-in customer, without exposing the secret key to the frontend.

This sounds fancier than it is: most teams using Stripe are effectively building this in-house. We just packaged the solution to save in-house teams from reinventing the wheel.

## Securing Stripe’s API for frontend access

To secure an API for frontend access, developers can refer to one, simple question:

> *What actions can a signed-in user perform on their own?*

Frontend APIs should be designed to power self-serve user interfaces. If the API is granted broader permissions, then a malicious actor may make unauthorized requests.

Luckily, Stripe’s API contains two objects that `use-stripe-subscription` leverages to determine which actions a user can perform on their own.

### The Customer object

In Stripe, every Subscription object belongs to a Customer object. The Customer object can represent an individual or a business.

As a long as an API can map the signed-in user to their Customer object, it’s trivial to restrict endpoints

- If a user *does not* have a Subscription, allow them to initialize a Checkout Session with their Customer ID to begin a new subscription
- If a user *does* have a Subscription, allow them to read the object, and to start a Customer Portal session to manage the subscription

### The Customer Portal Configuration object

Allowing users to start a Checkout Session from the frontend might sound unsafe – how can the API know which products a user is allowed to purchase on their own?

For this, we leverage Stripe’s Customer Portal product, which requires developers to specify which subscriptions a customer can switch between on their own:

![Refactoring Stripes Api For Frontend Access setup guide](./28f3676c57c3089778598df7cb781aa66675edb3-1764x948.png)

*Stripe’s Customer Portal settings page requires developers to configure which products a customer can switch between on their own*

Before `use-stripe-subscription` creates a Checkout Session, it verifies that the product is listed in the Customer Portal Configuration object. We assume that, if the configuration shows a customer is able to switch to a product, they should also be allowed to purchase that product new.

To make things easy for developers, the list of available subscription products is always accessible in the `products` attribute of the `useSubscription()` hook. This list is derived directly from the Customer Portal Configuration object.

## Passing in the Stripe Customer ID

To configure `use-stripe-subscription`, developers must create an endpoint on their server that communicates with Stripe’s API. The endpoint is responsible for retrieving the product list and current subscription information, as well as for generating Checkout and the Customer Portal sessions.

The package provides a complete Javascript implementation for this endpoint, except that developers must build their own function to determine the Stripe Customer ID associated with the request.

```javascript
import { subscriptionHandler } from 'use-stripe-subscription'

const handler = async (req, res) => {
  // Build your own findOrCreateCustomerId
  const customerId = await findOrCreateCustomerId(req)

  res.json(await subscriptionHandler({ customerId, query: req.query, body: req.body }))
}
```

This implementation is ideal because it works for both B2C and B2B subscription companies. The package doesn’t know (and therefore, is not opinionated about) whether the user is operating on behalf of a personal Customer object, or on behalf of a business’s Customer object.

## What about webhooks?

We know that frontend developers prefer to avoid webhooks, so `use-stripe-subscription` does not require them. Instead, it makes just-in-time API requests to Stripe to ensure it always has the latest data.

For very high-traffic websites, this strategy unfortunately has the potential to run into to Stripe’s API rate limit (100 read operations per second).

From our perspective, it’s quite unfortunate that Stripe asks developers to configure webhooks and setup a cache just to have access to updated data. It’s much simpler to query data directly from Stripe as it’s needed.

To alleviate this limitation, we investigating ways to add a robust caching solution to the package. Discussions and PRs toward this end are very much appreciated.

---

# Quickly Build a User Switcher, Just Like Gmail
URL: https://clerk.com/blog/build-a-user-switcher-just-like-gmail.md
Date: 2022-06-03
Category: Guides
Description: Build an app with complete authentication and a user switcher just like gmail has.

Developing an authentication system from scratch can be time-consuming, and the process can be prone to bugs. If you're looking for a customer identity platform that provides user management features like authentication, authorization, and management of user profiles, roles, and permissions, check out [Clerk](/). Clerk can save you time when it comes to building and testing your authentication flow. It also provides multi-session authentication, which allows users to seamlessly log in and switch between different accounts.

In this tutorial, you'll learn how to easily implement your own user profile switcher using Clerk and [Next.js](https://nextjs.org). You can follow along with this tutorial using [this GitHub repository](https://github.com/Anshuman71/clerk-user-switcher).

## What Is Clerk

Clerk is a one-stop solution for authentication and customer identity management. It helps you build a flawless user authentication flow that supports logging in with a password, multifactor authentication, or social logins with providers like [Google](/blog/nextjs-google-authentication), LinkedIn, Facebook, and GitHub. Clerk provides components like `<SignUp/>` and `<SignIn/>` that you can plug into your application right away to quickly build an authentication flow.

It's common for users to have multiple accounts for different purposes. For instance, you may have a personal YouTube channel for your friends and family, and another one specifically intended for your audience in your work as a developer. With Clerk’s multisession feature, you can seamlessly and intuitively switch between both accounts as needed.

## Building a User Switcher

Before you begin building a user switcher, you'll need a code editor like [Visual Studio Code](https://code.visualstudio.com/download). You'll also need [Node.js](https://nodejs.org/en) (version 14 or newer) and [npm](https://www.npmjs.com) installed.

[Create your Clerk account](https://dashboard.clerk.com/sign-up) by following the steps on their website. Once registered, navigate to the Clerk dashboard, where you'll begin this tutorial:

![Clerk dashboard home for starting the tutorial](./0bc55bf7d729c611963f855cae53cafe5d8acb63-3840x2160.png)

### Set Up the Project

To set up the project, run `npx create-next-app clerk-app` in your terminal. This will initialize a Next.js project. Then you need to run `npm install @clerk/nextjs` inside the project and open your [Clerk dashboard](https://dashboard.clerk.com) in a web browser. In the left navigation, click on **API Keys** and copy the **Frontend API key**, **Backend API keys** and **JWT verification key**:

![Clerk API keys page showing frontend and backend keys](./03c567841a526a3410b52ba746eab23708ac9990-3840x2160.png)

Save the keys copied above in a `.env.local` file inside your project:

```text {{ title: '.env.local' }}
NEXT_PUBLIC_CLERK_FRONTEND_API=<frontend-key>
CLERK_API_KEY=<backend-api-key>
CLERK_JWT_KEY=<jwt-verification-key>
```

### Set Up the Authentication Flow

The authentication flow of your application dictates how the users access different parts of your application. In this example, the user authentication flow works like this:

![User switcher flow diagram](./f2858db3eadd7bb4ff6eae2859b578e8a5ee217f-2264x1272.png)

To begin, implement the authentication flow in the `pages/_app.js`:

```jsx {{ title: 'pages/_app.js' }}
import { ClerkProvider, SignedIn, SignedOut } from '@clerk/nextjs'

import { useRouter } from 'next/router'

import Head from 'next/head'

import Link from 'next/link'

// pages that can be accessed without an active user session.

const publicPages = ['/', '/sign-in/[[...index]]', '/sign-up/[[...index]]']

const MyApp = ({ Component, pageProps }) => {
  const router = useRouter()

  return (
    <ClerkProvider {...pageProps}>
      <Head>
        <title>Clerk app</title>

        <link rel="icon" href="/favicon.ico" />

        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </Head>

      {/*If the route is for the home, sign-in and sign-up pages: show them without checks.*/}

      {publicPages.includes(router.pathname) ? (
        <Component {...pageProps} />
      ) : (
        <>
          {/*Show all pages if the user is signed in*/}

          <SignedIn>
            <Component {...pageProps} />
          </SignedIn>

          {/*Ask to sign in if the user isn't signed in*/}

          <SignedOut>
            <main>
              <p>
                Please{' '}
                <Link href="/sign-in">
                  <a>sign in</a>
                </Link>{' '}
                to access this page.
              </p>
            </main>
          </SignedOut>
        </>
      )}
    </ClerkProvider>
  )
}

export default MyApp
```

### Create the Sign-Up and Sign-In Pages

Next.js uses file-system-based routing, which makes it easy to create new pages. To learn more about Next.js routing check out their [official documentation](https://nextjs.org/docs/routing/introduction).

To create the sign-up and sign-in pages, navigate to the `pages/` folder in your project and create two new folders: `sign-up/` and `sign-in/`. Then create a new `[[...index]].js` file inside both of these folders. These routes will catch all the paths, including `/sign-up` and `/sign-in`.  You can read more about dynamic routing in the [Next.js documentation](https://nextjs.org/docs/routing/dynamic-routes#optional-catch-all-routes).

Use the prebuilt components for `<SignIn/>` and `<SignUp/>` to populate the pages:

```jsx {{ title: 'pages/sign-up/[[...index]].js' }}
import { SignUp } from '@clerk/nextjs'

const SignUpPage = () => <SignUp path="/sign-up" routing="path" signInUrl="/sign-in" />

export default SignUpPage
```

![Clerk SignUp component page screenshot](./baf4da4192af228f95122e38d5bb1c1cdef75f38-3840x2160.png)

```jsx {{ title: 'pages/sign-in/[[...index]].js' }}
import { SignIn } from '@clerk/nextjs'

const SignInPage = () => <SignIn path="/sign-in" routing="path" signUpUrl="/sign-up" />

export default SignInPage
```

![Clerk SignIn component page screenshot](./23a3986bedc299e0b5bd24170b1b10cb97c538e9-3840x2160.png)

### Create the Home Page

Now, the home page should display the greeting "Welcome to your new app." at the top of the page. If the user is signed in, it will show them their profile page. Otherwise, it will ask them to sign up or sign in:

![Home page with UserButton in navigation](./c911b489b95a6551e04b58ac4f8c1f59f6aec94b-1848x1080.png)

Update the `pages/index.js` file to use the `<SignedIn/>` component to conditionally render the child components if the user is signed in and use the `<SignedOut/>` component to render the child components if the user isn't signed in.

Inside the `<SignedIn/>` component, use the `<UserProfile/>` component provided by Clerk to show the user's profile details and allow them to edit their information.

You can also use the `<UserButton />` component in the top `<nav />` to allow users to manage their accounts and sign out of the application. The `<UserButton />` will render as a button with the user's avatar.

Inside the `<SignedOut/>`, render two `<Link />` components to send the user to the sign-in or sign-up page:

```jsx {{ title: 'pages/index.js' }}
import { SignedOut, SignedIn, UserProfile, UserButton } from '@clerk/nextjs'

import React from 'react'

import Link from 'next/link'

const Home = () => {
  return (
    <div
      style={{
        display: 'flex',

        justifyContent: 'center',

        alignItems: 'center',
      }}
    >
      <main>
        <nav
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <h1>Welcome to your new app.</h1>

          <UserButton />
        </nav>

        <div>
          <SignedIn>
            <UserProfile />
          </SignedIn>

          <SignedOut>
            <Link href="/sign-up">
              <a>Sign up </a>
            </Link>
            or
            <Link href="/sign-in">
              <a> Sign in </a>
            </Link>
            to get started.
          </SignedOut>
        </div>
      </main>
    </div>
  )
}

export default Home
```

If the user isn't signed in, the page will look like this:

![Signed-out state prompting sign-in](./c182a98f893cb71730e3ef707c27115f02b0e773-3840x2160.png)

Or if the user is signed in, it will look like this:

![Signed-in state with profile visible](./4c14e59c88acddeea0c8f6456b78f5816ddcac40-3840x2160.png)

When you click the user avatar at the top-right of your screen, a pop-up will appear containing buttons for **Manage account** and **Sign out**:

![User menu with Manage account and Sign out](./de1410f96d3edfc362d2a6cb29a1189dc80ff242-800x780.png)

### Implementing the User Switcher

Before moving on with this tutorial, you need to navigate to your [Clerk dashboard](https://dashboard.clerk.com) and enable the **Multi-session handling** feature inside the **Sessions** settings:

![Enable multi-session handling in Clerk dashboard](./c8b7ca26cacdedf785d37d16fa473ab7593f9b42-3840x2160.png)

After enabling multisession handling, go back to your application window and click on the user avatar again. Now you'll see that a new option, **Add account**, is available:

![Add account option shown in user menu](./103957875f33abe0dbf86e25a23739c7773a9468-914x1018.png)

Clicking on the **Add account** button will redirect users to the sign-in page, where they can sign in or sign up for a new account.

After signing in, Clerk will redirect the user back to the application with the new session, and the avatar pop-up menu will show all active sessions. The user can now switch between accounts by selecting them from the list:

![Multiple active sessions list in user switcher](./2b2198763b20ac5321eb634010ae6b3b907b7223-892x1310.png)

### Authenticating API Endpoints

To prevent malicious requests from coming through, it's essential to authenticate your API endpoints. With Clerk, you can access the user's authentication status in the Next.js API handlers. To do that, you must wrap your API handler function inside Clerk's `withAuth` higher-order function to access the `auth` property on the request object.

The following example uses the `request.auth` property to check if the `sessionId` is available and then sends the `userId` in the response. Otherwise, it returns a `401: Unauthorized` response code:

```jsx {{ title: 'pages/api/getUserId.js' }}
import { withAuth } from '@clerk/nextjs/api'

export default withAuth((request, response) => {
  const { sessionId, userId } = request.auth

  if (!sessionId) {
    return response.status(401).json({ id: null, message: 'No user signed in!' })
  }

  return response.status(200).json({ id: userId })
})
```

On the home page, add a button to request the API endpoint and show the user ID in an alert:

```jsx {{ title: 'pages/index.js' }}
import { SignedOut, SignedIn, UserProfile, SignOutButton, UserButton, useAuth } from '@clerk/nextjs'

import React from 'react'

import Link from 'next/link'

const Home = () => {
  function showUserId() {
    fetch('/api/getUserId')
      .then((res) => res.json())

      .then(({ id }) => {
        alert(`User id: ${id}`)
      })
  }

  return (
    <div
      style={{
        display: 'flex',

        justifyContent: 'center',

        alignItems: 'center',
      }}
    >
      <main>
        <nav
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <h1>Welcome to your new app.</h1>

          <UserButton />
        </nav>

        <div>
          <SignedIn>
            <button onClick={showUserId}>Show user ID</button>

            <UserProfile />

            <SignOutButton />
          </SignedIn>

          <SignedOut>
            <Link href="/sign-up">
              <a>Sign up </a>
            </Link>
            or
            <Link href="/sign-in">
              <a> Sign in </a>
            </Link>
            to get started.
          </SignedOut>
        </div>
      </main>
    </div>
  )
}

export default Home
```

After you've added this button, your user switcher is ready:

## Conclusion

After completing this tutorial, you will have successfully built a Next.js application that supports multisessions. While doing so, you learned about creating a new Next.js application, setting up a Clerk account, and integrating the Clerk SDK with your Next.js application.

You used the UI components provided by Clerk to create an authentication flow and user profile page. You also learned about the importance of multisession support in your application and how easy you can implement it with Clerk. Lastly, you created an API route in Next.js and secured it with Clerk.

Using the Clerk SDK, you can expand on the example above to add social logins and multifactor authentication to your application.

---

# The New Wave Stack
URL: https://clerk.com/blog/new-wave-stack.md
Date: 2022-06-02
Category: Insights
Description: A custom Remix stack with Clerk, Fauna, and Netlify.

### Introduction

In March 2022, Remix introduced a feature of the Remix CLI called [Remix Stacks](https://remix.run/docs/en/v1/pages/stacks). This allows you to quickly and easily generate a Remix project from a pre-created template. These custom stacks are named after music genres. At Clerk, we’re all about making the developer experience as easy as possible, so we knew this was a perfect opportunity to combine the best of Remix’s development tools with Clerk’s easy-to-use user management and authentication platform.

New wave music was defined by the transition from the punk music scene to a more radio-friendly form of pop expressionism. In many ways, Modern Web tools like Clerk, Netlify, and Fauna represent much of the same thing for building web applications. Clerk’s custom Remix stack takes the DIY (Punk) freedom of designing an app the way you want and combines it with production-ready (Pop) resources to make your product accessible to a broader audience.

Welcome to The New Wave Stack. Let’s get happy.

[Check out the official New Wave Stack repo on GitHub](https://github.com/charles-clerk-dev/new-wave-stack)

The critical parts of any [custom Remix stack](https://remix.run/docs/en/v1/pages/stacks) are:

- Automatic deployment - Netlify
- Authentication - Clerk
- Database - Fauna
- Testing - Cypress, RTL, Jest
- Linting/Formatting/TypeScript - ESLint, Prettier

### Deployment with Netlify

![New Wave Stack guide illustration](./23c422b3064e352482ca1ef726c956c37cd2c6f1-2512x1956.png)

While it may seem odd to start with deployment, it can often be much more challenging to configure later on in the development process. If you can get deployment set up early and test deployment often, it can save you an incredible amount of stress in the future.

This stack is all about making things easy for developers, so Netlify was an obvious choice for deployment. Netlify allows you to connect a git repository and set up deployments to happen when a branch is merged into production. Or, if you prefer to deploy manually, Netlify has an easy-to-use CLI. It also provides deployment previews, rollbacks to previous deployments, and many other great features that make getting your application in front of users incredibly simple.

### Authentication with Clerk

![New Wave Stack guide illustration](./797d984b2bba456fef1e9c742471727709885a7c-2512x1956.png)

The New Wave Stack comes with Clerk’s complete authentication and user management features. This means that developers don’t have to worry about building many of the things users have come to expect from web applications. Components like Sign In, Sign Up, and User Profiles are available from the ground up. Clerk’s wide variety of authentication options will allow you the flexibility to manage your users the way you want. Setting up an account on Clerk takes seconds, and configuring your New Wave app is as simple as adding your API keys.

### Database management with Fauna

> \[!WARNING]
> Fauna’s service [ended on May 30, 2025](https://web.archive.org/web/20250319171743/https://fauna.com/blog/the-future-of-fauna), but they’ve [open-sourced their codebase](https://faunadb.org).

![New Wave Stack guide illustration](./ec7408c71780a250c4cd2a01a20782c992e50d5f-2046x1796.png)

Fauna is an excellent cloud-based database solution that combines the flexibility of NoSQL systems with the relational querying capabilities of SQL databases into a transactional database with GraphQL support and other modern features, such as real-time streaming.

Although Fauna offers built-in identity, authentication, and password management functionality, it requires that you manage the user data yourself. Clerk provides features like social SSO, passwordless authentication, multi-session management, and more without the hassle of managing your user and identity service. Clerk’s JSON Web Token (JWT) Templates feature makes it easy to authenticate queries to your Fauna database.

We have [a comprehensive walkthrough](/tutorials/build-movie-emoji-quiz-with-remix-fauna-and-clerk#set-up-fauna-database) on building an application with Remix, Clerk, and Fauna. Working through this tutorial will give you a solid understanding of how to set up your first Fauna database and how to query the database from your Remix application. It’s also quite a lot of fun.

### Styling with Tailwind

Like everything else in this stack, our approach to styling is to provide the tool that allows you to build your application quickly and efficiently, which is why we configured The New Wave Stack to use Tailwind out of the box. Tailwind is possibly the most common solution for developers styling their Remix applications, and there are plenty of good reasons why. It allows for inline styling, which can speed up development time, and the generated CSS file for even large applications is usually less than 10kb.

### Testing with Cypress/Testing Library

Developer experience is always a primary focus for Clerk, so we chose to configure this stack with Cypress for end-to-end testing. Cypress is commonly used in Remix stacks as it provides an effortless and straightforward testing environment. We’re sticking with the classic Testing Library/Jest combo for lower-level tests.

### Formatting

Finally, we arrive at the last few touches that make your code sparkle. We’ve set up Prettier for formatting, ESLint to take care of linting, and TypeScript to manage typing.

### Conclusion

It was a lot of fun building out the New Wave Stack and discovering how each piece seemed to fit naturally with the others. One of the benefits of Modern Web tools is the intuitive way they can be made to work together. It’s getting faster and easier for talented developers to take an idea and immediately begin putting it together. We want people to spend as little time as possible on setting up their app so that they can focus their effort on what makes their project special and unique.

---

# Three best practices for building React REST SDKs
URL: https://clerk.com/blog/best-practices-for-building-react-rest-sdks.md
Date: 2022-05-20
Category: Engineering
Description: For optimal developer experience, React SDKs require completely different patterns than Node

## 1. No secret keys allowed

This may be obvious but it must be stated as #1. Since React hooks run in the browser, SDKs cannot use secret keys for API access.

Instead, the API should be designed to scope access based on the currently signed-in user. Then, a session token or a JWT can be used to authorize requests to the API.

## 2. GETs should be Hooks

This is the critical change that turns a Node SDK into a React SDK. In Node SDKs, GET methods usually return a Promise:

```jsx
import { getUser } from '@clerk/nextjs'

const user = await getUser()
```

Unfortunately, using a Promise in a React Component is a big headache. The developer needs to add `useEffect` and `useState` hooks to render a loading state while the Promise is pending, then update when the resolves.

The end result is quite verbose and hard to decipher:

```jsx
import { useEffect, useState } from 'react'
import { getUser } from '@clerk/nextjs'

const UserProfile = () => {
  const [user, setUser] = useState(null)
  useEffect(() => {
    const load = async () => {
      const res = await getUser()
      setUser(res)
    }
    load()
  }, [getUser, setData])
  if (!user) {
    return <div>Loading</div>
  }
  return <div>Name: {user.name}</div>
}
```

The solution is to provide developers with a hook instead of a Promise. Hooks are composable, so under the hood this is still built with `useEffect` and `useState`, it just doesn't burden the developer with setting them up manually:

```jsx
import { useUser } from '@clerk/nextjs'

const UserProfile = () => {
  const { user } = useUser()
  if (!user) {
    return <div>Loading</div>
  }
  return <div>Name: {user.name}</div>
}
```

That's much easier to use!

## 3. Hooks should "react" to mutations

There is still a problem in the example above. What if the user wants to change their name and the developer triggers an update:

```jsx
user.update({ name: 'Ben Bitdiddle' })
```

By default, the `useUser` hook in our `<UserProfile/>` component won't automatically refresh. But since it's a hook, developers will expect it to – that's the whole point of React!

There are two high-level strategies to refreshing the hook, **eager refresh** and **sequential refresh**.

### Eager refresh

Eager refresh is the most performant solution, but it can be hard to configure. The idea is that the API endpoint behind `user.update()` should return the updated User object in its response body. When the response is received, `user.update()` can propogate the new value to any components calling `useUser()`.

This example isn't particularly hard to configure because the mutation is contained to the `User` object. It can be achieved with a globally-scoped React context to store the value of the User object, instead of using `useState` directly in the `useUser` hook.

Eager refresh is much harder to configure when there are side effects involved. For example, at Clerk we have a `SignIn` object that is responsible for tracking the state of a sign-in flow while the user completes their first and second factor. Once the user successfully signs in, it has the side effect of generating a `Session` object, which changes the application's state from signed-out to signed-in.

We achieve eager refresh when a sign in completes by returning both the `SignIn` object and `Session` object from the server, but establishing a clean pattern for this has proven easier-said-than-done.

### Sequential refresh

The alternative to eager refresh is sequential refresh, which is less performant but can be easier to configure, especially when side effects are possible.

Using our example above, instead of trying to return both `SignIn` and the new `Session` at once, the final `SignIn` endpoint can instead return only the `SignIn` resource.

When the client sees that the `SignIn` is complete, though, it knows that a new `Session` must exist. So, it can trigger a second request to retrieve the new `Session`.

Two round-trips to the server will inherently be slower than one, but the development burden of eager refresh may make sequential refresh a viable alternative – especially as edge compute has made round-trips less costly over time.

---

# Next.js SSR authentication with Clerk
URL: https://clerk.com/blog/next-js-ssr-authentication-with-clerk.md
Date: 2022-05-07
Category: Engineering
Description: Next.js SSR authentication is easy with Clerk – just a few lines of code to get started.

## What is Server-Side Rendering (SSR) for React?

\*\*\
Update (11/2/2023):\*\* The code examples shown in this post have been deprecated. For the most up-to-date code examples on how to use Clerk with Next.js SSR, [read the documentation](/docs/references/nextjs/read-session-data#pages-router). Additionally we have a [new blog](/blog/nextjs-auth-clerk-streamlined-ssr-efficiency).

*Updated: 25/08/2022*

React was originally built to run on the client. Once React started, hooks would run to load data, and eventually a full page would be generated.

But since React is just a Javascript library, there was no reason it couldn't run on a server, too. **Server-side rendering** (SSR) runs React on the server to generate a page's initial HTML (a.k.a the first *render*), then runs React again on the client to provide reactivity.

Server-side rendering is particularly helpful for pages that must be indexed in search engines, since search engines cannot index pages that are rendered client-side.

The bigger benefit, though, is that server-side render can reduce the complexity of an application and lead to fewer lines of code. This is especially true in the modern era, where frameworks like Next.js provide helpers that drastically reduce the setup time for SSR.

### How to use SSR with Next.js?

Server-side rendering can be used by including `export async function getServerSideProps()` on any pages you need SSR. Below is an example of how a page would look when using SSR:

```jsx
function Page({ data }) {
  // use the data on our page
  ;<div>{data.content}</div>
}

export async function getServerSideProps() {
  // Fetch data from an API
  const res = await fetch(`https://api.example.com/data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

export default Page
```

This example retrieves some data from api.example.com. Then, we pass the data to the UI using the return statement. Finally, in the UI, we present the data to the user.

*You can read more about Server-side rendering in the [Next.js SSR documentation](https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props).*

Now that you have a basic understanding of how SSR works, let us investigate how Clerk and SSR can work together.

## How to use Clerk with SSR?

Clerk allows you to verify a user is authenticated and to retrieve user profile data when using SSR. Below, we will cover how to implement both.

### Securing pages with SSR

With Clerk and Next.js SSR, we can check if the user is authenticated and, if not, redirect them to the sign-in page without rendering anything on the client. Clerk provides a helper called `withServerSideAuth`, which allows you to access authentication information:

```jsx
import { withServerSideAuth } from '@clerk/nextjs/ssr'

export const getServerSideProps = withServerSideAuth(({ req, resolvedUrl }) => {
  const { sessionId } = req.auth

  if (!sessionId) {
    return { redirect: { destination: '/sign-in?redirect_url=' + resolvedUrl } }
  }

  return { props: {} }
})
```

The snippet above checks to see if there is a session. If not, it will redirect the user to the sign-in page. Once the user has successfully authenticated, Clerk will redirect the user back to the page they were initially trying to access. Here is a quick GIF showing the process in action.

![Next Js Ssr Authentication With Clerk guide illustration](./5db59e3e9f8e6c84c2ff95e84b0c21439ceeea8c-2560x1440.png)

*If you want to see it in action, check out this [fully functional example](https://replit.com/@perkinsjr/Clerk-SSR-Auth-Example) that contains all the code you need for SSR authentication with a redirect back.*

### Retrieving userId or JWT templates

Server-side rendering gives you the opportunity to retrieve data from 3rd party APIs and your own database. When using Clerk, you have the option of retrieving the user ID, or if you are using a Clerk integration such as Hasura you can also retrieve the JWT ready for use.

Below is an example of retrieving a Hasura JWT token ready to retrieve data before sending the page to the user.

```jsx
import { withServerSideAuth } from '@clerk/nextjs/ssr'

export const getServerSideProps = withServerSideAuth(async ({ req }) => {
  const { sessionId, getToken } = req.auth

  if (!sessionId) {
    return { redirect: { destination: '/sign-in?redirect_url=' + resolvedUrl } }
  }
  // use a token for your Clerk integrations
  const hasuraToken = await getToken({ template: 'hasura' })

  // retrieve data from your Hasura integration

  return { props: {} }
})
```

If you aren’t using a JWT template or a Clerk integration you can just retrieve the userId and use that against your own database.

```jsx
import { withServerSideAuth } from '@clerk/nextjs/ssr'

export const getServerSideProps = withServerSideAuth(async ({ req }) => {
  const { sessionId, userId } = req.auth

  if (!sessionId) {
    return { redirect: { destination: '/sign-in?redirect_url=' + resolvedUrl } }
  }

  // use the userId to retrieve your own data

  return { props: {} }
})
```

## Enabling Full SSR Mode

In some cases, you may need the full User object available to you. For example, if you need to retrieve the user’s primary email address

Clerk can use an additional network request to retrieve the full User object. To enable it, you will need to add `{ loadUser: true }` to your SSR request. Then, the complete User object will be available:

```jsx
import { withServerSideAuth } from '@clerk/nextjs/ssr'

export const getServerSideProps = withServerSideAuth(
  async ({ req, resolvedUrl }) => {
    const { sessionId, getToken, userId } = req.auth
    // retrieve the user object
    const { user } = req
    // return the users primary email address.
    const email = user.emailAddresses.find((email) => {
      return email.id === user.primaryEmailAddressId
    })

    // retrieve data using the email address.
    const data = getDataFromEmail(email)

    return { props: { data } }
  },
  { loadUser: true },
)
```

## **Ready to add auth to your app?**

Be sure to visit our [Next.js authentication with Clerk page](/nextjs-authentication) today to better understand how you can add authentication in minutes - not weeks.

Want to connect with other developers? Join our [Discord community](https://clerk.com/discord) or follow [@clerk on X](https://x.com/clerk) to stay up to date with the latest features, improvements, and sneak peeks to Clerk.

---

# How to skip CORS preflights and speed up your API with polyfills
URL: https://clerk.com/blog/skip-cors-options-preflight.md
Date: 2022-04-29
Category: Engineering
Description: CORS preflights add unnecessary latency to requests. Learn to use "simple" requests to skip the preflight entirely.

At Clerk, we have an API that is directly accessible from the frontend (we call it the Frontend API). It exclusively handles cross-origin requests, but none of those requests trigger a CORS preflight.

This is by design. CORS preflights do not add security for modern applications and they add an extra network round-trip, so we made sure that every API request is considered a "simple request."

## What do you mean CORS preflights do not add security?

It's a common misconception that CORS preflight requests add security to modern applications. Why else would they exist?

Surprisingly, CORS preflights exist to protect old applications, not new ones.

Specifically, the CORS designers were concerned about old applications that incorrectly assumed that browsers would never allow request methods besides GET or POST, or would never allow custom HTTP headers.

When browsers added the capability to send alternative request methods and custom headers via `fetch` (and its older sibling, `XMLHttpRequest`), suddenly applications that made this assumption were at risk.

To mitigate the risk to old applications, an extra "preflight" request was added to requests with PATCH, PUT, DELETE methods, and to requests with custom headers. The idea is that, if those applications fail to respond to the preflight in a very specific way, then the actual request will never be dispatched.

It's dirty and it adds latency, but it works.

The annoying part is: modern applications that anticipate PATCH, PUT, DELETE requests and custom headers don't gain any security from CORS preflights, it's just extra latency they need to incur to protect legacy applications. In 2022, it's like robbing Peter to pay an exceptionally stubborn Paul who won't update their decades old codebase, but we digress...

## How can CORS preflights be skipped?

Certain cross-origin requests are classified as "simple requests" and do not require a successful preflight before being dispatched.

Based on the section above, it might be easy to guess which requests qualify as simple: GET or POST requests without custom headers. *(Note: This is a slight simplification, the full details are [available on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests).)*

To build an API that doesn't trigger preflights, we need to design polyfills for modern request methods and custom headers.

### One critical point first

The polyfills below assume you have configured your CORS middleware to outright reject requests that should not be processed.

As an example, consider CORS middleware running on `api.example.com` that is configured to allow the Origin of `https://www.example.com`.

Now, consider a request comes in with the Origin of `https://randomattacker.com`

Does your CORS middleware reject this request, or does it allow the request to be processed?

**It depends on your middleware.**

Some middleware might simply add an access-control header (below), then allow the request to continue:

```text
Access-Control-Allow-Origin: https://www.example.com
```

This header doesn't stop the request from being processed, but it does stop the browser from reading your server's response.

**This is not the behavior you want.**

Instead, you want your middleware compare the received Origin to the allowed Origin, and immediately cancel the request if they don't match.

**The only way to confirm your middleware's behavior is to write your own tests.** Clerk needed to write our own middleware to reject requests with undesirable CORS options (origin, credentials, etc).

### Polyfilling request methods

Polyfilling the request method is trivial - and we were fortunate to have inspiration [from Ruby on Rails](https://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-patch-put-or-delete-methods-work-questionmark). Every mutation request to our frontend API is dispatched as a POST, but the method can be overridden using a query string like `?_method=PATCH`. In our backend, we run middleware to ensure that the request is treated as a PATCH when this query string is present.

### Polyfilling custom headers

Custom headers can be more challenging to polyfill. It really depends on what type of content you're putting in the header:

- If the header *does not* contain sensitive information, the polyfill can use the same query string approach used above for request methods
- If the header *does* contain sensitive information, the polyfill should be handled within the the request body

Typically, developers want to customize two headers:

1. **Content-Type:** To set it to **application/json**. This is not sensitive and can be polyfilled using the query string.
2. **Authorization:** To include an access token. This is sensitive and should not be polyfilled using the query string.

It's important that sensitive information is not added to the query string because the request path is often logged to tools like bug trackers and analytics software. To obscure this information from those tools, it's better to add the field to the request body. In the case of the Authorization header, an extra form value or JSON attribute will suffice.

## That's everything!

These simple changes will eliminate CORS preflight requests from a frontend talking to a frontend API. In the process, it eliminates a round trip, which can easily take over 100ms if your user is geographically far from your server. Even in the best case of edge computing, this strategy will likely shave off \~20ms from your overall response time.

For the modern web, every millisecond counts!

---

# The future of authentication is both stateful and stateless
URL: https://clerk.com/blog/future-of-auth-stateless-and-stateful.md
Date: 2022-04-28
Category: Insights
Description: Stateful authentication is more secure. Stateless authentication is faster. A hybrid approach delivers the best of both worlds.

Should session authentication be stateless or stateful? This simple question has been the source of many spirited debates, especially on Hacker News where it's [spurred](https://news.ycombinator.com/item?id=21783303) [many](https://news.ycombinator.com/item?id=18353874) [lively](https://news.ycombinator.com/item?id=16517412) [threads](https://news.ycombinator.com/item?id=18804875) over the years.

The discussion always boils down to two primary points:

1. Stateful authentication is more secure
2. Stateless authentication is faster

In this post, we'll first discuss the reasons behind both, and explain how a hybrid approach offers the best of both worlds.

## What is stateless? What is stateful?

This post will be hard to follow if you don't know the difference between stateful and stateless authentication, so let's start from there.

### Stateful authentication

Stateful authentication relies on a database (or another mechanism for storing "state") to determine if a session is still active.

When a session begins, a unique identifier is created to be passed along with future web requests.

When requests are received, that unique identifier is used to query the database and check if the session is still active.

### Stateless authentication

Stateless authentication relies on cryptography to determine if a session is still active.

When a session begins, a cryptographically signed token is generated (usually in the form of a JWT) that encodes the user's ID and the timestamp when the session expires. This token is then passed along with future web requests.

When requests are received, the backend confirms that the token's signature is valid and that it has not expired. This is considered stateless because no database is involved, just cryptography to verify the signature.

## Stateful authentication is more secure

The first issue to consider is security. Love it or hate it, security is the most important feature on any authentication system.

Stateful authentication is considered more secure because the database can be updated at any time to mark the session as inactive. When the next request is received, the backend will notice the change and refuse the request.

Since the database is checked on every request, instantaneous session revocation is possible. This is ideal if an attacker has access to a system and needs to be stopped immediately.

With stateless authentication, though, the backend only inspects the token. No database is involved, so the token will remain valid until the hardcoded expiration is passed. So, if an attacker gets hold of a token, their attack can continue until the expiration passes.

## Stateless authentication is faster

Since stateful authentication is more secure, you might expect it's the easy choice. It's not, because stateless authentication is *significantly* faster.

The cryptography required for stateless authentication can consistently be performed in under 1 millisecond.

On the other hand, the database query required for stateful authentication can take 10-20 milliseconds.

Authentication happens on every request, so the performance hit of a stateful approach quickly starts to look like a common bottleneck. As a result, developers start looking for faster alternatives, and naturally gravitate toward stateless authentication.

## Hybrid stateful and stateless authentication offers the best of both worlds

Fortunately, authentication is not a zero-sum game. Developers can build a hybrid approach of stateful *and* stateless authentication that is both fast and secure.

The magic comes from a simple sleight-of-hand: instead of setting stateless tokens to expire with the session, they can be set with a short expiration and refreshed periodically.

When a token is refreshed, the database is checked to ensure the session is still active. As a result, sessions can still be revoked before they end. The potential delay before revocation completes depends on how frequently tokens must be refreshed. If a 60 second expiration is assigned to each token, then revocation will take a maximum of 60 seconds.

Refreshing stateless tokens is a stateful process, since it requires querying the database to confirm the session is still active. But with the optimal approach, refreshes will happen asynchronously, except for the very first load after an application is closed.

### In practice

Clerk changed to a hybrid approach for session management 6 months ago. The functionality is built-in to our SDKs without any configuration, so most developers don't even recognize it's happening.

Our stateless authentication tokens are set to expire every 60 seconds. In practice, here's how it works:

1. When a user signs in, a stateless authentication token is created immediately.
2. An asynchronous poller is started on the frontend to refresh the stateless token every 50 seconds. The 10 second difference is to account for potential network delays and clock-skew between our token generator and the developer's backend.
3. While the user is active on the application, every request to the developer's backend will include an active, stateless authentication token.

But now, let's say the user closes the application for a few minutes so our poller stops. When the user revisits the application, the latest token has already expired since 60 seconds have elapsed.

In this case, we need to update the token synchronously before requests to the backend can be processed. It's the one exception to an otherwise completely stateless authentication experience.

In the end, Clerk's authentication solution is both stateful and stateless. Sessions can be revoked within 60 seconds, yet the vast majority of requests use stateless authentication and can be verified in under 1ms.

## Conclusion

To address speed and security concerns, we believe the future of authentication is both stateful and stateless. We've been using this solution for over 6 months and it has proven to be robust and resilient over many millions of refreshes and authentications.

Our [session management](/features/session-management) is included free in every Clerk plan - give it a try to test for yourself, or watch your network tab while signed in on [clerk.dev](/) to see it in action!