Guides & Tutorials

Learn how to implement authentication in your Next.js application using SuperTokens.

SuperTokens is an open-source identity management solution that provides secure and easy-to-use authentication and session management for your web applications. In this guide, we will explore how to integrate SuperTokens into a Next.js application for seamless user authentication.

Last updated on October 5, 2023 at 4:05 PM

Author's avatar

Krste Rajchevski

Software Engineer @ Bugpilot

Annoyed by React errors?
Bugpilot is the error monitoring platform for React. Catch unexpected errors, troubleshoot, and fix with our AI assistant. Learn more and create an account to start your 14-day free trial.


Before we begin, make sure you have the following installed on your machine:

  • Node.js (v12 or higher)
  • Next.js (v10 or higher)
  • npm or yarn package manager


To get started, you need to install the SuperTokens package by running the following command in your Next.js project directory:

npm install supertokens-auth-react supertokens-node

Or if you're using yarn:

yarn add supertokens-auth-react supertokens-node


Once the installation is complete, we need to configure SuperTokens in our Next.js application.
First, create a file called auth.js in your project's root directory, and add the following code:

1// auth.js
2import { supertokens } from "supertokens-node";
4export default function initializeSuperTokens() {
5  supertokens.init({
6    supertokens: {
7      connectionURI: "https://api.supertokens.io/0/auth",
8    },
9    appInfo: {
10      appName: "Your App Name",
11      apiDomain: "http://localhost:3001",
12      websiteDomain: "http://localhost:3000",
13    },
14  });

Make sure to replace Your App Name with the actual name of your application.
Next, open your Next.js' pages/_app.js file and add the following lines:

1// pages/_app.js
2import { useEffect } from "react";
3import initializeSuperTokens from "../auth";
5export default function App({ Component, pageProps }) {
6  useEffect(() => {
7    initializeSuperTokens();
8  }, []);
9  return <Component {...pageProps} />;

This will initialize SuperTokens when your application starts.


Now that SuperTokens is set up, we can start implementing the authentication flow.
Let's create a simple login page /pages/login.js in your Next.js project with the following code:

1// pages/login.js
2import { useState } from "react";
3import { signIn } from "supertokens-auth-react";
5export default function LoginPage() {
6  const [email, setEmail] = useState("");
7  const [password, setPassword] = useState("");
8  const handleLogin = async (e) => {
9    e.preventDefault();
10    try {
11      await signIn(email, password);
12      // Redirect or perform actions after successful login
13    } catch (error) {
14      // Handle login error
15    }
16  };
17  return (
18    <form onSubmit={handleLogin}>
19      <input
20        type="email"
21        placeholder="Email"
22        value={email}
23        onChange={(e) => setEmail(e.target.value)}
24      />
25      <input
26        type="password"
27        placeholder="Password"
28        value={password}
29        onChange={(e) => setPassword(e.target.value)}
30      />
31      <button type="submit">Login</button>
32    </form>
33  );

In the handleLogin function, we use the signIn function from supertokens-auth-react to authenticate the user. Upon successful authentication, you can perform any necessary actions, such as redirecting to a different page or updating the user interface.

Protecting Routes

To protect certain routes in your Next.js application, you can leverage the withAuth Higher Order Component (HOC) provided by SuperTokens.
For example, let's say you want to protect the /dashboard page. Create a file called /pages/dashboard.js with the following code:

1// pages/dashboard.js
2import { useSession } from "supertokens-auth-react";
4export default function DashboardPage() {
5  const { session } = useSession();
6  if (!session) {
7    // Redirect or show error message for unauthorized access
8    return null;
9  }
11  // Continue rendering the dashboard for authenticated users
12  return (
13    <div>
14      <h1>Welcome to the Dashboard</h1>
15      {/* ... */}
16    </div>
17  );

The useSession hook allows you to access the user's session information. If there is no active session, you can handle unauthorized access accordingly.
Next, open your /pages/_app.js file and update it as follows:

1// pages/_app.js
2import { useEffect } from "react";
3import { withAuth } from "supertokens-auth-react";
4import initializeSuperTokens from "../auth";
6export default withAuth(function App({ Component, pageProps }) {
7  useEffect(() => {
8    initializeSuperTokens();
9  }, []);
10  return <Component {...pageProps} />;

By wrapping your app component with the withAuth HOC, SuperTokens will automatically handle session validation and redirect unauthenticated users to the login page.


In this guide, we have explored the process of adding authentication to a Next.js application using SuperTokens. With SuperTokens, you can easily implement secure user authentication and protect routes within your Next.js app. Remember to consult the SuperTokens documentation for various authentication and session management options.
Give it a try and enhance the security of your Next.js applications!
Happy coding!

Annoyed by React errors?
Bugpilot is the error monitoring platform for React. Catch unexpected errors, troubleshoot, and fix with our AI assistant. Learn more and create an account to start your 14-day free trial.

Get Bugpilot