Add authentication and user management to your Next.js React app using the new Next.js Edge Runtime and the Ory Kratos open source project! This example also contains end-to-end tests! To deploy the full and working project, hit the button:
If you like watching videos instead of reading text, watch Vincent's video tutorial!
Ory Kratos Open Source Identity Platform
Ory Kratos is a full-featured, free, and open source authentication and identity management platform. It supports multi-factor authentication with FIDO2, TOTP, and OTP; Social Sign In, custom identity models; registration, profile management, account recovery, administrative user management and so much more! In contrast to other identity systems, Ory Kratos enables you to build your own login, registration, account settings, account verification (e.g. email, phone, activate account), account verification (e.g. reset password) user interfaces and user flows using dead-simple APIs. This guide focuses on integrating with Ory Kratos' session and login APIs. If you are interested in building your own UI, check out Add Custom Login, Registration, User Settings to Your Next.js & React Single Page Application (SPA)
Before we start, let's get some terminology out of the way:
- At Ory, identity can mean any actor in a system (user, robot, service account,
...). The term
user
always refers to a human being sitting in front of a browser or mobile app. - A session refers to a user's session in a browser or mobile app after they have authenticated.
- Self-Service refers to flows the user can do on their own - such as login, registration, and so on. It does not require administrative / support intervention.
Next.js Authentication with Ory Kratos
If you want to see a live demo right away, check out this app in action.
You can find the source code for this guide on GitHub. To give it a spin, clone it and run the following commands:
git clone https://github.com/ory/kratos-nextjs-react-example.git
cd kratos-nextjs-react-example
npm i
Per default, this app uses the public playground deployment of Ory Kratos at
https://playground.projects.oryapis.com
. To use it, simply run:
npm run dev
If you want to use your own Ory Kratos instance, you can use the
ORY_KRATOS_URL
or ORY_SDK_URL
environment variable. The easiest way to run
Ory Kratos is in an
Ory Cloud Project
(free for developers)! In that case, set the ORY_SDK_URL
to your
project's SDK url:
# If you run Ory Kratos in Ory Cloud:
export ORY_SDK_URL=https://my-project.projects.oryapis.com
You may also run Ory Kratos in a local environment. A quick way to begin is to run the Ory Kratos Docker quickstart:
git clone --depth 1 --branch master https://github.com/ory/kratos.git
cd kratos
git checkout master
git pull -ff
docker-compose -f quickstart.yml -f contrib/quickstart/kratos/cloud/quickstart.yml up --build --force-recreate -d
In that case, set the environment variable ORY_SDK_URL
to your local Ory
Kratos instance:
# If you run Ory Kratos locally using the Docker quick start:
export ORY_KRATOS_URL=http://localhost:4455/
# Start the app
npm run dev
Next head over to http://localhost:3000/ to see the app in action with login, registration - a working user management!
Create a Next.js Single Page App with Ory Kratos from Scratch
To add login / auth to your Next.js app, first create a new Next.js project
npx create-next-app@latest --typescript
and install the Ory Kratos SDK as well as Ory's NodeJS integration helpers
npm i --save @ory/integrations @ory/kratos-client
Then we will add Ory's Next.js Edge-Integration helpers to our project, which will act as a tunnel to Ory Kratos. You can either conveniently copy this route from our reference application
curl -o "pages/api/.ory/[...paths].ts" --create-dirs \
https://raw.githubusercontent.com/ory/kratos-nextjs-react-example/master/pages/api/.ory/%5B...paths%5D.ts
or manually create a file called pages/api/.ory/[...paths].js
in your NextJS
project and copy the following contents:
Add the Ory Kratos SDK to your Next.js App
Great, now you have a NextJS app with a login route. If the user is authenticated we want to show the session. If the user is not signed in, we want to offer a way to sign up or sign in! Let's take a look at the home page. First, we need to add the Ory Kratos SDK to our Next.js app:
Easy, right? The package @ory/integrations
takes care of all the heavy lifting
for you and sets up the SDK so that it connects with the Next.js Edge function
we created in the step prior.
React Hook to Find Out if a User is Authenticated
Next let's figure out if the user is authenticated. We will use a React Hook to check this. We also want to track any errors that may happen as well as creating a logout url.
Adding Login and Registration Links if the User is Not Authenticated
Let's also show the user a login and registration link if the user has no login session yet
or the account settings and logout link if the user is authenticated!
As you can see, it is really easy to initialize login, registration, and profile updates. Just create a link!
<a href="/api/.ory/self-service/login/browser">
will initialize the login flow.<a href="/api/.ory/self-service/registration/browser">
will initialize the registration flow.<a href="/api/.ory/self-service/settings/browser">
will initialize the account settings flow (needs login).<a href="/api/.ory/self-service/verification/browser">
will initialize the (email, phone, ...) verification flow.<a href="/api/.ory/self-service/recovery/browser">
will initialize the (password, 2fa, ...) recovery flow.
Adding a Logout Link for Authenticated Users
To prevent certain types of attack vectors, such as Denial of Service, Ory Kratos provides a secure logout mechanism. This involves first fetching a logout URL from the Ory Kratos API and then redirecting the user to that URL if logout is requested:
If we do not bind the logout URL to the user's session, it means that anyone could load e.g. an image with the logout URL and logout the user without user interaction:
<img src="https://www.example.org/my-vulnerable-logout-command" />
Ory Kratos protects you from these type of attacks with the flow shown above.
Putting it all Together
You've made it! Clone the app and try it out right now!
git clone https://github.com/ory/kratos-nextjs-react-example.git
cd kratos-nextjs-react-example
npm i
Or look at the code we wrote above in full below:
Deploy to Vercel
The easiest way to deploy your Next.js app is to use the Vercel Platform from the creators of Next.js. If you have never deployed on Vercel, check out the Next.js deployment documentation for more details. Deploying the app is easy. Ensure that your build works by running
npm run build
Then, set up your Vercel account and create a new app. You will need to configure your Ory Cloud Project SDK URL or the URL of your self-hosted Ory Kratos instance in your Vercel deployment:
By the way! If you want to use separate Ory Kratos deployments for staging, production, and development then use different SDK URLs for the different environments by un/selecting the checkboxes in the Vercel UI:
If you want to call Ory Cloud's Admin APIs from your Next.js Edge serverless functions, optionally set up the Ory Personal Access Token:
Next all you need to do is to run the deploy command and connect it to the project you created:
npx vercel deploy --prod
This also works with Vercel PR Preview!
End-to-End Tests
Adding end-to-end tests is also easy! Clone the repository and run the following commands:
git clone https://github.com/ory/kratos-nextjs-react-example.git
cd kratos-nextjs-react-example
npm i
Then, depending on your setup, you can either use Ory Kratos local or deployed in Ory Cloud:
export ORY_KRATOS_URL=https://playground.projects.oryapis.com/
Then, build and start the server
npm run dev
and in a new shell run the end-to-end tests:
npm run test:dev
You can find the full spec file in the cypress/integration/pages.spec.js
file:
The GitHub Action file is also straight forward and contains two configurations, one for running Ory Kratos locally and one for running Ory Kratos in Ory Cloud:
Conclusion
Adding login and registration to your Next.js app is a breeze with open source technology like Ory Kratos and Next.js.
We hope you enjoyed this guide and found it helpful! If you have any questions, check out the Ory community on Slack and GitHub!