DEV Community

Giovanni Fu Lin
Giovanni Fu Lin

Posted on

## Frontend with Google Sign in + Token

Recommended frontend starter: next-auth + prisma
https://github.com/steven-tey/precedent

Get environment variables GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET + API_KEY
https://console.cloud.google.com/apis/credentials

Google OAuth 2.0 App Sign in

for > next-auth v4 with Prisma adapter.

// [...nextauth].ts

import prisma from "@/lib/prisma";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import NextAuth, { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  callbacks: {
    async session({ session, token, user }) {
      const getToken = await prisma.account.findFirst({
        where: {
          userId: user.id,
        },
      });

      let accessToken: string | null = null;
      if (getToken) {
        accessToken = getToken.access_token!;
      }

      session.user.token = accessToken;
      return session;
    },
  },
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
};

export default NextAuth(authOptions);
Enter fullscreen mode Exit fullscreen mode

If you are using typescript. Create a /types directory inside your source folder and add a next-auth-d.ts file inside of it.

// next-auth.d.ts

import NextAuth, { DefaultSession } from "next-auth";

declare module "next-auth" {
  /**
   * Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
   */
  interface Session {
    user: {
      /** Oauth access token */
      token?: accessToken;
    } & DefaultSession["user"];
  }
}
Enter fullscreen mode Exit fullscreen mode

access the session from clientside:

import React from "react";
import { useSession, signIn, signOut } from "next-auth/react";

type Props = {};

function ExampleComponent({}: Props) {
  const { data: session } = useSession();

  if (session) {
    return (
      <>
        Access token {session.user.token} <br />
        <button onClick={() => signOut()}>Sign out</button>
      </>
    );
  }
  return (
    <>
      Not signed in <br />
      <button onClick={() => signIn("discord")}>Sign in with Discord</button>
    </>
  );
}

export default ExampleComponent;
Enter fullscreen mode Exit fullscreen mode

Credits and useful links

https://stackoverflow.com/questions/69068495/how-to-get-the-provider-access-token-in-next-auth/74883310#74883310

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay