Skip to main content

Step by step

This guide will walk you through the steps to add Kraken authentication to your Next.js app. When you're done, you'll know how the different parts of the package work together in order to provide a seamless authentication experience for your users.

Note: Most functions mentioned in this guide have more options and parameters than the ones shown here. Please refer to the API reference for more information + rely on the TypeScript types.

Step 1: Install the package

First, you'll need to install the @krakentech/blueprint-auth package. You can install this package via npm with a Kraken issued organisation token with the right permissions - please get in touch if you need one.

pnpm add @krakentech/blueprint-auth

Step 2: next.config.js

There's a known issue with @tanstack/react-query when hooks that use it are created in a different package so you'll need to add a webpack config wrapper to fix this issue.

Reference: https://github.com/TanStack/query/issues/3595

const { withBlueprintAuth } = require('@krakentech/blueprint-auth');

module.exports = {
webpack: (config, context) => {
...
return withBlueprintAuth({ config, context });
},
...
};

API reference

Step 3: middleware.ts

You'll need to add our authHandler to your Next.js's middleware file so that it can intercept all requests to protected routes and handle the authentication flow.

import { NextResponse, type NextRequest } from 'next/server';
import { authMiddleware } from '@krakentech/blueprint-auth';

export async function middleware(req: NextRequest) {
const res = NextResponse.next();

return await authMiddleware({
req,
res,
krakenConfig,
appRoutes,
});
}

API reference

Step 4: API routes

You'll have to create 4 different API routes to handle the authentication flow. We recommend using the following structure:

  • pages/api/auth/login.ts
  • pages/api/auth/logout.ts
  • pages/api/auth/session.ts
  • pages/api/graphql.ts (every client-side request to Kraken's API should go through this route)

These routes are used by the package's hooks (e.g. useLogin, useLogout, useSession) to handle the authentication flow.

pages/api/auth/login.ts

import type { NextApiRequest, NextApiResponse } from 'next';
import { loginHandler } from '@krakentech/blueprint-auth';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
await loginHandler({
req,
res,
krakenConfig,
});
}

API reference

pages/api/auth/logout.ts

import type { NextApiRequest, NextApiResponse } from 'next';
import { logoutHandler } from '@krakentech/blueprint-auth';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
logoutHandler({ req, res });
}

API reference

pages/api/auth/session.ts

import type { NextApiRequest, NextApiResponse } from 'next';
import { sessionHandler } from '@krakentech/blueprint-auth';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
sessionHandler({ req, res });
}

API reference

pages/api/graphql.ts

import { NextApiRequest, NextApiResponse } from 'next';
import { graphqlHandler } from '@krakentech/blueprint-auth';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
await graphqlHandler({
req,
res,
krakenConfig,
});
}

API reference

Step 5: Wrap your app with the AuthProvider

You'll need to wrap your app with the AuthProvider component so that the auth hooks can work properly.

import { AuthProvider } from '@krakentech/blueprint-auth';

const App = ({ children }) => {
return (
<AuthProvider
appRoutes={appRoutes}
apiRoutes={apiRoutes}
handlers={handlers}
>
{children}
</AuthProvider>
);
};

API reference

Step 6: Use the hooks

You can now use the hooks provided by the package to handle the authentication flow in your app.

import { useLogin, useLogout, useSession } from '@krakentech/blueprint-auth';

const LoginButton = () => {
const { mutate } = useLogin();

return <button onClick={() => mutate({ email, password })}>Login</button>;
};

const LogoutButton = () => {
const { mutate } = useLogout();

return <button onClick={mutate}>Logout</button>;
};

const LoginPage = () => {
const { isAuthenticated } = useSession();

return (
<div>
{isAuthenticated ? (
<>
<p>Welcome back!</p>
<LogoutButton />
</>
) : (
<>
<p>Please login to access this page</p>
<LoginButton />
</>
)}
</div>
);
};

API reference

Step 7: Prefetch the session data on the server (optional)

You can prefetch the session data on the server by using the prefetchSession function. This will ensure that the user's session is available on the client-side as soon as the page loads.

Only relevant in pages that use server-side rendering (getServerSideProps) and/or the useSession hook.

import { QueryClient, dehydrate } from '@tanstack/react-query';
import { prefetchSession } from '@krakentech/blueprint-auth';

export const getServerSideProps: GetServerSideProps = async (context) => {
const queryClient = new QueryClient();

await prefetchSession({
queryClient,
context,
});

return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
};

API reference


As you can see from the steps above, almost every single function relies on having the other ones set up correctly. Namely, the api routes need to be setup properly along with the AuthProvider in order for the hooks to work as expected.

That's it! You've successfully added Kraken authentication to your Next.js app. If you have any questions or need help, please get in touch.