Easy Google and GitHub Authentication with Next.js using Clerk Auth: Step-by-Step Guide and Best Practices

Integrating Google and GitHub authentication into your Next.js projects doesn't have to be overwhelming. Whether you're an experienced Next.js developer or just starting out, this comprehensive guide will provide you with a clear roadmap and easy-to-follow steps. We'll walk you through setting up API credentials, handling authentication flows, and implementing best practices for a secure user experience. By the end of this article, you'll have the knowledge to effortlessly leverage the power of Google and GitHub authentication in your Next.js applications. Let's dive in and simplify the world of Next.js authentication!

Integrating Google Authentication using Clerk Auth

Clerk Auth is an amazing tool that makes google and github authentication really easy. Make sure you have set up your Next js project.

Step 1

Install the clerk auth package in your project terminal.

npm install @clerk/nextjs

Step 2

Visit the Clerk Auth website.

Click on the button above, "Start building for free". You'll be redirected to a page to sign up on the platform. Once you've signed up, you will be taken to a page.

Step 3

This page is the dashboard where you get started in setting up your single sign-on details.

Click on "Add application".

Step 4

You'll be taken to this page, where you can set up your authentication page.

On this page, you have different authentication options, like Google, Github, Phone Number, Email address, and so on. All you need to do is give the application a name, then toggle the buttons beside your preferred authentication method, then click on "CREATE APPLICATION".

Step 5

After clicking on the "CREATE APPLICATION" button, you should find your self on the page below.

Based on the image above, you can see that we have environment variables. All you need to do is copy the .env.local details, then go back to your code environment.

Step 6

Create a file in your Next js project environment called .env.local and paste the details you copied from the previous step there.

Step 7

Now what we need to do is navigate to our root layout.tsx file. This is the layout.tsx file that comes with your new next js application. Once you've navigated to that file, it should look like this.

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 }) {
  return (
      <html lang="en">
        <body className={inter.className}>{children}</body>
      </html>
  )
}

Now you need to add the <ClerkProvider> wrapper.

The <ClerkProvider> component wraps your Next.js application to provide active session and user context to Clerk's hooks and other components. It is recommended that the <ClerkProvider> wraps the <body> to enable the context to be accessible anywhere within the app.

Once you've added the <ClerkProvider> wrapper, your code should look something like this:

// app/layout.tsx
import './globals.css'
import { Inter } from 'next/font/google'
import { ClerkProvider } from '@clerk/nextjs'

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 (
    <ClerkProvider>
      <html lang="en">
        <body className={inter.className}>{children}</body>
      </html>
    </ClerkProvider>
  )
}

Step 8

We need to protect our application. This means that we need to decide what pages should be made public and what pages should be hidden behind the authentication.

How we do this is by creating a middleware.ts file in the root folder (it could be the app folder or the src folder, depending on whichever one you are using).

The middleware.ts file should look like this

import { authMiddleware } from "@clerk/nextjs";

export default authMiddleware();

export const config = {
  matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};

Because of this, your entire application is secured; if you attempt to access it, a redirect to your sign-up page will appear.

Step 9

Let's build our SignUp and SignIn pages.

Clerk Auth allows us to create this very easily. All you need to do is create a folder inside your app or src folder called sign-up, then create another folder inside your sign-up folder called [[...sign-up]], then create a file inside the [[...sign-up]] called page.tsx.

This is what you put on the page.tsx file:

import { SignUp } from "@clerk/nextjs";

export default function Page() {
  return <SignUp />;
}

And that's all for the SignUp page.

We then repeat the same process for the sign-in page.

All you need to do is create a folder inside your app or src folder called sign-in, then create another folder inside your sign-in folder called [[...sign-in]], then create a file inside the [[...sign-in]] called page.tsx.

This is what you put on the page.tsx file:

import { SignIn } from "@clerk/nextjs";

export default function Page() {
  return <SignIn />;
}

Step 10

Next up we need to add these environment variables to the .env.local file.

NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/

When you sign in or register and click on the corresponding links at the bottom of each component, these environment variables determine how the components behave.

Your .env.local file should look like this at the end of the day.

NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_cHJvbXB0LW1hcnRlbi0yNy5jbGVyay5hY2NvdW50cy5kZXYk
CLERK_SECRET_KEY=sk_test_N7jDjDyteJ7I4wfEzE8LCU7oTpzMBv3Rz03w5SKmVw

NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/

Step 11

The final step is to add a UserButton Component.

The <UserButton /> allows you to manage your account information and log out, thus allowing you to complete a full authentication circle. You can add it anywhere you want, next to the logo in app/page.tsx is a good start.

You can now add this code to your Navigation menu of your project in the app/page.tsx file

//app/page.tsx
import { UserButton } from "@clerk/nextjs";

export default function Home() {
  return (
    <div>
      <UserButton afterSignOutUrl="/"/>
    </div>
  )
}

Now we have fully set up our Google and GitHub authentication in the simplest way possible.

Hope this was helpful!!!