vercel / ai-chatbot

A full-featured, hackable Next.js AI chatbot built by Vercel
https://chat.vercel.ai
Other
5.51k stars 1.62k forks source link

Google OAuth #363

Closed VistritPandey closed 1 month ago

VistritPandey commented 1 month ago

Hi, I am trying to add Google OAuth, but for some reason I am getting a api/auth/error 404 If I am trying to use the code as given in the next-auth (which follows the pages/ [...nextauth].ts format), it does not work but at the same time I wonder that as in the current version it has the credentials based login, it should work. So I tried adding google as a provider in auth.config.ts and auth.ts but none of them worked. Here is what I had

import type { NextAuthConfig } from 'next-auth'
import GoogleProvider from "next-auth/providers/google"

export const authConfig = {
  secret: process.env.AUTH_SECRET,
  pages: {
    signIn: '/login',
    newUser: '/signup'
  },
  callbacks: {
    async authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user
      const isOnLoginPage = nextUrl.pathname.startsWith('/login')
      const isOnSignupPage = nextUrl.pathname.startsWith('/signup')

      if (isLoggedIn) {
        if (isOnLoginPage || isOnSignupPage) {
          return Response.redirect(new URL('/', nextUrl))
        }
      }

      return true
    },
    async jwt({ token, user }) {
      if (user) {
        token = { ...token, id: user.id }
      }

      return token
    },
    async session({ session, token }) {
      if (token) {
        const { id } = token as { id: string }
        const { user } = session

        session = { ...session, user: { ...user, id } }
      }

      return session
    }
  },
  providers: [
    GoogleProvider({
      clientId: "SOME_KEY",
      clientSecret: "some_key",
    }),
  ]
} satisfies NextAuthConfig
VistritPandey commented 1 month ago

Found a fix:

  1. Move the providers from auth.config.ts to auth.ts
  2. create a new file inside the directory app/api/auth/[...nextauth]/ called route.ts and paste the following line of code: export { GET, POST } from '@/auth';
  3. In your auth.ts add this in export: handlers: { GET, POST },