Adding authentation with clerk
make it simple
- tags
- auth
- nextjs
- clerk
- vercel
Contents
Clerk is a way to add authentication to your site that can be done in under 10 minutes. This is table stakes and why reimplement the wheel?
Create the clerk app
Go to clerk.com and signup.
Add you app name and select the login providers. Keep this window open.
Create the nextjs app
|
|
Answer the questions and then go into the directory, and install @clerk/nextjs
:
|
|
Add middleware.ts
We set up the middleware which is used to protect the routes that we
want. In this case, it'll be /dashboard
.
|
|
Update the layout.tsx
- Surround everything with
ClerkProvider
- Create a header that has the
SignedOut
,SignInButton
,SignedIn
, andUserButton
.
SignedOut
and SignedIn
will render their children when the user is
either signed out or in.
SignInButton
will trigger the login flow.
And UserButton
will show the dropdown with the user avatar that lets
the person manage their account.
|
|
Homepage
In the main page, we can show off a few things.
- Showing the Signout button if the user is signed in
- Showing the Signin button otherwise
- Linking to the dashboard page
|
|
Client Side Access
To get access to the user on the client side, make sure that you have
the 'use client'
directive on the front of you page and access the
user and session information with useUser
and useSession
.
|
|
API/Server access
Lets see how we can get access to the user with the api:
|
|
Now if you hit http://localhost:3000/api from the browser and you are logged in, you should see your user information in the request.
Deploying to Vercel
Now that we have this working, lets try and get it deployed onto the web using Vercel.
First make sure that you've pushed your code to github.
Then create a new vercel app from that repo.
Then copy and paste in your .env.local file into the environment.
And press deploy.
And it just works!
You'll probably want to add a domain on both the vercel and clerk side of things but this is enough to get going.
Previously
Next