Introduction to Next-Auth
Next-Auth is a flexible and easy-to-implement authentication library for Next.js applications. It provides a full suite of features that cover various authentication strategies including OAuth, Email/Password, and Social Logins with providers like Google, Facebook, etc. Next-Auth simplifies session management, making it a go-to choice for modern web applications.
Setting Up Next-Auth
To get started with Next-Auth, install the necessary packages:
npm install next-auth @next-authProviders
Now, create a [...nextauth].js
file in the pages/api/auth
directory:
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
export default NextAuth({
providers: [
Providers.Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET
}),
// Add more providers here
],
database: process.env.DATABASE_URL
});
Authentication APIs
Next-Auth offers various API endpoints for managing authentication:
Signing In
import { signIn } from 'next-auth/client';
const handleSignIn = async () => {
await signIn('google');
};
Trigger the signIn
function to initiate the login process with a supported provider.
Signing Out
import { signOut } from 'next-auth/client';
const handleSignOut = async () => {
await signOut();
};
Use the signOut
function for logging out users.
Getting Session
import { getSession } from 'next-auth/client';
const fetchSession = async () => {
const session = await getSession();
console.log(session);
};
The getSession
function retrieves the user’s session data.
Protecting Pages
import { getSession } from 'next-auth/client';
export async function getServerSideProps(context) {
const session = await getSession(context);
if (!session) {
return {
redirect: {
destination: '/auth/signin',
permanent: false
}
}
}
return {
props: { session }
};
}
Use getServerSideProps
to protect routes in your Next.js application.
Example App
Here’s a basic example application demonstrating the use of Next-Auth APIs:
import { Provider } from 'next-auth/client';
export default function App({ Component, pageProps }) {
return (
);
}
The above code sets up the Next-Auth Provider
in your application, ensuring that session data is available throughout your app.