At first, we need to create a firebase project, go to authentication, enable google sign in provider and get the web client id and secret
now we bootstrap a next js project with npx create-next-app@latest
we don't remove anything from the index file, we'll keep it as it is, mostly we will be focusing on the functional parts and the UI. After this, we install next auth.
edit the _app.js, wrap the entire thing with session providers from next-auth
Create a folder auth inside pages/api and then create [...nextauth].js file inside the auth folder
don't mess up the folder structure and the naming conventions, if you do so it will result in errors.
we create .env.local file in the root of the folder to store ower sensitive information. this is where we put ower google provider secret and id that we got from firebase
the NEXTAUTH_URL and JWT_SECRET are necessary we can read about it in the docs.
provider is an array, we can pass multiple providers like Twitter, Facebook, Spotify here we are working with google provider so we only pass one single provider
in the google provider we pass in two values the clientId and the client secret these are the same values we got from our firebase
inside the callbacks, we have a session that returns the user after signing in, as we have wrapped our application with a session provider this is available to the whole application. Lastly, we pass the secret.
now we got to our index.js file and edit it to this
In index.js we do ssr with getServerSideProps to get the providers and session and return it. The providers will return all the providers, in our case Google sign-in and session. We get the session from useSession hook in line no 8 and then in line no. 10 we check if the session is empty i.e now user logged in we return the login component with the providers passed as a prop
Inside the login.js, we map the providers, as I have mentioned we can provide multiple providers, so providers is an array. In line no 10, in the button we get the signIn function from next-auth which is built-in and works across all the providers.
Now when we run npm run dev we get this as an output in our browser
now when you will click on this button you will get an error
what we have to do is copy the redirect uri, got to our google cloud console, select our project, navigate to credentials, in credentials select Oauth 2.0 client
Inside Oauth 2.0, in the authorised redirect URL options, paste your redirect uri
now when you back and click on the sign in button it will show you with all the google accounts you have at the moment, choose one and it will sign you in
In our index.js we add a logout button to signout, we use the built in signout function from next-auth
now when you click on the logout button it will log you out.
the code is available in my github