Installation
Welcome to the Next.js Installation Guide for FullAuth. Follow these steps to integrate FullAuth seamlessly into your Next.js project for a secure and user-friendly authentication experience.
Install Packages:
npm i @fullauth/core @fullauth/next @fullauth/react
or
yarn add @fullauth/core @fullauth/next @fullauth/react
Add Environment Variables:
NEXT_PUBLIC_FULLAUTH_URL= your-backend-url
Create Route Handler:
In your Nextjs App directory, create a route.ts file inside app/api/auth/[...fullauth] folder
app/api/auth/[...fullauth]/route.ts
import { AuthOptions } from '@fullauth/core';
import { NextHandler } from '@fullauth/next';
import { CredentialProvider } from '@fullauth/core/providers';
export const authOptions: AuthOptions = {
providers: [
CredentialProvider({
name: 'credentials',
credentials: {
email: { type: 'text', placeholder: 'Email' },
password: {
type: 'password',
placeholder: 'Password',
},
},
async signIn(credentials) {
try {
// you verification logic here
// throw errors and catch them on the client side
// throw new Error('No User');
return {
email: credentials.email,
id: 'test1',
name: 'test',
};
} catch (error: any) {
console.log(error);
throw error;
}
},
}),
],
// add the secret to encrypt the session
secret: process.env.FULLAUTH_SECRET!,
};
const handler = NextHandler(authOptions);
export { handler as GET, handler as POST };
All requests to /api/auth/* will automatically be handled by FullAuth.
Session Provider:
In order to access the session object on the client side, we need to wrap our app with SessionProivder
app/layout.tsx
import { SessionProvider } from '@fullauth/react';
import { getSession } from '@fullauth/next/helpers';
import { authOptions } from './api/auth/[...fullauth]/route';
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
// you need to pass the handler option to getSession to get the session on the server
const session = await getSession(authOptions);
return (
<html lang="en">
<body >
<SessionProvider session={session}>{children}</SessionProvider>
</body>
</html>
);
}
then in your page.tsx file you can call useSession() hook to access the session object.
You can check our examples for more details.
Usefull Links