OAuth Authentication in Next.js: A Guide to Secure Third-Party Logins

Share:

Using OAuth for Third-Party Authentication in a Next.js App

Authentication is a critical aspect of any web application. In modern apps, using third-party authentication via OAuth providers like Google, GitHub, Facebook, or Twitter provides a seamless and secure login experience for users. In this post, we’ll walk through how to implement OAuth in a Next.js application using NextAuth.js, a powerful authentication library tailored for Next.js.


—

Why Use OAuth in Your App?

OAuth allows users to log in with their existing accounts from popular services, improving convenience and trust. Benefits include:

Faster sign-up/login

Reduced need for password management

Enhanced security

Access to additional user data (with permission)



—

Setting Up OAuth with NextAuth.js in Next.js

Let’s break it down step-by-step:

1. Initialize Your Next.js App

If you don’t already have a project:

npx create-next-app@latest my-auth-app
cd my-auth-app

Install NextAuth.js:

npm install next-auth


—

2. Configure API Route for Authentication

Create a new file at:

/pages/api/auth/[…nextauth].js

Here’s a basic configuration using Google as an example:

import NextAuth from “next-auth”;
import GoogleProvider from “next-auth/providers/google”;

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
});


—

3. Set Up Environment Variables

Create a .env.local file in the root of your project:

GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
NEXTAUTH_SECRET=your-random-secret-key
NEXTAUTH_URL=http://localhost:3000

You can generate NEXTAUTH_SECRET using:

openssl rand -base64 32


—

4. Add Sign-In and Sign-Out UI

In any page or component, import the signIn and signOut functions:

import { signIn, signOut, useSession } from “next-auth/react”;

export default function AuthComponent() {
  const { data: session } = useSession();

  if (session) {
    return (
      <>
        <p>Welcome, {session.user.name}</p>
        <button onClick={() => signOut()}>Sign out</button>
      </>
    );
  }

  return <button onClick={() => signIn(“google”)}>Sign in with Google</button>;
}

Don’t forget to wrap your app in the SessionProvider in _app.js:

import { SessionProvider } from “next-auth/react”;

export default function App({ Component, pageProps }) {
  return (
    <SessionProvider session={pageProps.session}>
      <Component {…pageProps} />
    </SessionProvider>
  );
}


—

Adding Other Providers

NextAuth.js supports many providers like GitHub, Twitter, Facebook, etc. To add GitHub, for example:

import GitHubProvider from “next-auth/providers/github”;

GitHubProvider({
  clientId: process.env.GITHUB_ID,
  clientSecret: process.env.GITHUB_SECRET,
});

Add corresponding variables to your .env.local file.


—

Conclusion

OAuth simplifies the login experience while enhancing security. Using NextAuth.js with Next.js, you can quickly integrate third-party providers like Google and GitHub into your app. As your app grows, NextAuth also supports database sessions, JWTs, and role-based access control.

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Now