I am trying to do authentication using google in my next js and strapi app.
However, I keep getting the error below:
Error: This action with HTTP GET is not supported by NextAuth.js
.
This is the code from 'api/auth/[...nextauth].jsx'
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
const options = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
secret: process?.env?.NEXT_PUBLIC_SECRET,
callbacks: {
async session({ session, token }) {
session.jwt = token.jwt;
session.id = token.id;
return session;
},
async jwt({ token, user, account }) {
if (user) {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/auth/${account.provider}/callback?access_token=${account.access_token}`
);
const data = await response.json();
token.jwt = data.jwt;
token.id = data.user.id;
}
return token;
},
},
};
const Auth = (req, res) => NextAuth(req, res, options);
export default Auth;
I have set the redirect URIs in the google console to be :
https://frontend.com/api/auth/callback/google
https://backend.com/api/auth/callback/google
Also, I have set the redirect URI in strapi to be :
https://frontend.com/api/auth/callback/google
So there was something I didn't like about the auth flow initially but didn't know how to work around it either.
It's the fact that next auth had to come into play. For what? I didn't like it either explained for the right reasons or not.
Then, I worked around a miracle.
I created a new file [provider].js
inside /pages/auth
.
Notice its not inside the /pages/api/auth
import React from "react";
import { api } from "../../services/api";
export async function getServerSideProps({
params: { provider },
query: { access_token },
...ctx
}) {
const res = await api(
`/auth/${provider}/callback?access_token=${access_token}`,
"GET"
);
if (res?.jwt) {
//do something
}
return {
props: { },
};
}
const Connect = () => {
return (
<div>
Redirecting...
</div>
);
};
export default Connect;
The redirect URL to my front-end app:
http://localhost:3000/auth/google
In Google console: Under Credentials -> OAuth 2.0 Client IDs:
Authorized redirect URIs:
http://localhost:1337/connect/google/callback
http://localhost:3000/auth/callback/google
And I got this working fine even in production.