Consumer Authentication

/

Quickstarts

/

Quickstarts

/

Next.js

Next.js Quickstart

This quickstart guide covers the essential steps to start integrating Stytch’s Consumer Authentication in a Next.js application.

Overview

Stytch offers developers a Next.js SDK which includes pre-built UI components with customizable login and signup forms, alongside a collection of headless methods for integrating with your own custom UI.

For server-side rendering (SSR) support, you'll also need to integrate our Node SDK.

In this guide, we will walk your through initial set up of an email magic links flow login form with our prebuilt UI components.

Want to skip straight to the source code? Check out the App Router example app or the Page Router example app.

Getting started

1
Install Stytch SDKs and configure your API keys

If you haven't already, create a Stytch Consumer project in your Stytch Dashboard.

Add our frontend NextJS SDK package to your Next.js application:

npm install @stytch/nextjs @stytch/vanilla-js --save

Add your Stytch project's public_token to your application as an environment variable in a .env file:

# .env
# The below values may be found in your Stytch Dashboard: https://stytch.com/dashboard/api-keys
NEXT_PUBLIC_STYTCH_PROJECT_ENV=test
NEXT_PUBLIC_STYTCH_PUBLIC_TOKEN="YOUR_STYTCH_PUBLIC_TOKEN"

2
Configure Stytch SDK settings

To allow the Stytch SDK to run on your frontend, you'll also need to:

  1. Enable frontend SDKs in Test in your Stytch Dashboard here.
  2. Add the domain your application will run on (e.g. http://localhost:3000) to the list of Domains under Authorized applications.

3
Create the UI client and wrap your application in <StytchProvider>

First, initialize the Stytch UI client by invoking the createStytchUIClient constructor function, passing in your Project's public token.

Next, pass the Stytch UI client to the StytchProvider component at the root of your application, making it accessible to all child components.

// pages/_app.jsx
import { StytchProvider } from '@stytch/nextjs';
import { createStytchUIClient } from '@stytch/nextjs/ui';

// optional object for configuring SDK cookie behavior, currently showing defaults
const stytchOptions = {
  cookieOptions: {
    opaqueTokenCookieName: "stytch_session",
    jwtCookieName: "stytch_session_jwt",
    path: "",
    availableToSubdomains: false,
    domain: "",
  }
}

const stytchClient = createStytchUIClient(
  process.env.NEXT_PUBLIC_STYTCH_PUBLIC_TOKEN,
  stytchOptions
);

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <Head>
         // Truncated
      </Head>

      {/* Wrap the application with StytchProvider to make the SDK available in children components */}
      <StytchProvider stytch={stytchClient}>
        <main>
          <div className="container">
            <Component {...pageProps} />
          </div>
        </main>
      </StytchProvider>
    </>
  );
}

4
Add the <StytchLogin> UI component

Create a StytchLogin component. You can configure which authentication flow and methods you'd like to offer by modifying the products field in your config object. Here's an example that utilizes our Email Magic Links product:

// src/components/LoginOrSignupForm.jsx
import { StytchLogin } from '@stytch/nextjs';
import { Products } from '@stytch/vanilla-js';

const REDIRECT_URL = 'http://localhost:3000/authenticate';

export const LoginOrSignupForm = () => {
    const styles = {
    container: {
      width: "100%",
    },
    buttons: {
      primary: {
        backgroundColor: "#4A37BE",
        borderColor: "#4A37BE",
      },
    },
  };
  
  const config = {
    products: [Products.emailMagicLinks],
    emailMagicLinksOptions: {
      loginRedirectURL: REDIRECT_URL,
      loginExpirationMinutes: 60,
      signupRedirectURL: REDIRECT_URL,
      signupExpirationMinutes: 60,
    },
  };

  return <StytchLogin config={config} styles={styles} />;
};

For Email Magic Links, you must specify a redirect URL in your Project's Dashboard to authenticate the token. By default, the redirect URL is set to http://localhost:3000/authenticate.

If the <StytchLogin> component is rendered on the redirect URL used for this flow, the Email Magic Link token will automatically be authenticated. You can specify additional Redirect URLs in your Project's Dashboard, and override the default by passing in an explicit emailMagicLinksOptions.loginRedirectURL to your UI config.

You can read more about redirect URLs in this guide.

5
Add the <LoginOrSignupForm> component to your login page

Finally, add the LoginOrSignupForm component we just created to the /authenticate page. You'll notice that we check for a logged-in user before displaying the LoginOrSignupForm component.

// pages/authenticate.jsx
import { useEffect } from "react";
import { useRouter } from "next/router";
import { useStytch, useStytchUser } from "@stytch/nextjs";
import { LoginOrSignupForm } from "src/components/LoginOrSignupForm";

export default function Authenticate() {
  const { user, isInitialized } = useStytchUser();
  const stytch = useStytch();
  const router = useRouter();

  useEffect(() => {
    if (stytch && !user && isInitialized) {
      const tokenType = router.query.stytch_token_type;
      const token = router.query.token;
      if (token && tokenType === 'magic_links') {
        stytch.magicLinks.authenticate(token, {
          session_duration_minutes: 60,
        });
      }
    }
  }, [isInitialized, router, stytch, user]);

  useEffect(() => {
    if (isInitialized && user) {
      // Redirect the user to an authenticated page if they are already logged in
      router.replace("/dashboard");
    }
  }, [user, isInitialized, router]);

  return <LoginOrSignupForm />;
}

6
What's next

Check out our product-specific guides for how to handle full authentication flows for each product you'd like to support, like Email Magic Links and OAuth.