NextJS protect API routes using Google OAuth

Viewed 19

I am having troubles understanding how to protect an API with next-auth using Google authentication, I have searched a lot online but there is not a good guide on how to achieve this, at the moment I have created the [...nextauth].js as follows:

import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
import connection from "../../../lib/database";

const options = {
  secret: process.env.JWT_SECRET,
  adapter: MongoDBAdapter(connection),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  pages: {
    signIn: '/signin'
  },
  callbacks: {
    async signIn({ user, account, profile, email, credentials }) {
      return true;
    },
    async redirect({ url, baseUrl }) {
      return baseUrl;
    },
    async session({ session, user, token }) {
      return session;
    },
    async jwt({ token, user, account, profile, isNewUser }) {
      return token;
    }
  }
}

export default (req, res) => NextAuth(req, res, options)

The effect I am trying to achieve is to send the accessToken to the api on each request, when the api receives the request validates the token and if the token is ok then sends the response otherwise redirects the user to the /signin page.

I believe I should add the token in the axios Bearer in the signin callback am I right? However I have no idea on how to write the middleware that checks if the jwt token is correct.

0 Answers
Related