Skip to content

Next.JS App Router

React Auth Kit provides an easy way to enable authentication in a Next.Js Application. After integration, you can use all the React Auth Kit core functionalities in the Next App.

Info

As of now, React Auth Kit only supports Client Side Rendering(CSR) of User Data and redirection. Implementation of Server Side Rendering(SSR) will be implemented in the future release.


Store Creation

To use React Auth Kit in the application, we first need to create the store that holds the data for our application. You can create the store in a separate file.

Import

Import createStore in your app
import createStore from 'react-auth-kit/createStore';

Usage

src/store.{js|ts}
1
2
3
4
5
6
const store = createStore({
  authName:'_auth',
  authType:'cookie',
  cookieDomain: window.location.hostname,
  cookieSecure: window.location.protocol === 'https:',
});

Provider

React Auth Kit uses React's context Provider API. So we'll use the provided guide by Varcel to implement context API in the Next Js application. Read the vercel provided blog

In the Provider file, we'll initialize the AuthProvider and pass the store.

app/provider.js
"use client"; // (1)

import React from 'react';
import createStore from 'react-auth-kit/createStore';
import AuthProvider from 'react-auth-kit/AuthProvider';

const store = createStore({
    authName:"__auth",
    authType:"cookie",
    cookieDomain:'127.0.0.1',
    cookieSecure:false,
})

const Providers = ({
    children,
  }: {
    children: React.ReactNode
  }) => {

  return (
    <AuthProvider store={store}>
      {children}
    </AuthProvider>
  )
}

export default Providers;
  1. 🙋‍♂️ We are required to use use client;, because the provider will only render on the client side.

Integrate with the Application

We now have to take the Provider, and integrate it with the RootLayout so use it in the application. Providers added in the RootLayout are visible throughout the application.

import Providers from './providers'; // (1)

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <Providers> // (2)
      <html lang="en">
        <body>
            {children}
        </body>
      </html>
    </Providers>
  )
}
  1. Importing the previously created Providers component.
  2. Wrap the whole Application inside the Provider.

Example

The complete example is available in examples/create-next-ts-route

API


— 🔑 —

React Auth Kit is MIT License code