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

Top comments (0)