Home > AI > Frontend > Next.js >

NextAuth.js with Google Provider (localhost)

This video is very useful and the GitHub repo is here https://github.com/vahid-nejad/google-provider-next-auth

Get client-id and client-secret from Google

Visit https://next-auth.js.org/providers/google and access the Google Console at https://console.cloud.google.com/apis/credentials. The configurations are outlined below.

# Type 

Web Application 

# Authorized JavaScript origins
https://localhost:3000

# Authorized redirect URIs
http://localhost:3000/api/auth/callback/google

Copy the client-id and client-secret to .env file

GOOGLE_CLIENT_ID=??
GOOGLE_CLIENT_SECRET=??

The pertinent codes can be found here.

app/layout.tsx

import Appbar from "./components/Appbar";
import Providers from "./components/Providers";
import "./globals.css";
import { Inter } from "next/font/google";

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <Providers>
          <Appbar />

          {children}
        </Providers>
      </body>
    </html>
  );
}

app/api/auth/[..nextauth]/route.tsx

import NextAuth from "next-auth/next";
import GoogleProvider from "next-auth/providers/google";

const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID ?? "",
      clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? "",
    }),
  ],
});

export { handler as GET, handler as POST };

app/components/Appbar.tsx

import React from "react";
import SigninButton from "./SigninButton";

const Appbar = () => {
  return (
    <header className="flex gap-4 p-4 bg-gradient-to-b from-white to-gray-200 shadow">
      <SigninButton />
    </header>
  );
};

export default Appbar;

app/components/Providers.tsx

"use client";
import { SessionProvider } from "next-auth/react";
import React, { ReactNode } from "react";

interface Props {
  children: ReactNode;
}

const Providers = (props: Props) => {
  return <SessionProvider>{props.children}</SessionProvider>;
};

export default Providers;

app/components/SigninButton.tsx

"use client";
import React from "react";
import { signIn, signOut, useSession } from "next-auth/react";
const SigninButton = () => {
  const { data: session } = useSession();

  if (session && session.user) {
    return (
      <div className="flex gap-4 ml-auto">
        <p className="text-sky-600">{session.user.name}</p>
        <button onClick={() => signOut()} className="text-red-600">
          Sign Out
        </button>
      </div>
    );
  }
  return (
    <button onClick={() => signIn()} className="text-green-600 ml-auto">
      Sign In
    </button>
  );
};

export default SigninButton;

Leave a Reply