nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.19k stars 3.36k forks source link

getProviders doesn't work on getServerSideProps #3521

Closed akhfaern closed 2 years ago

akhfaern commented 2 years ago

Description 🐜

when calling getProviders on getServerSideProps it generates an error and returns null

Is this a bug in your own project?

Yes

How to reproduce ☕️

export async function getServerSideProps(context) {
  const providers = await getProviders();

  return {
    props: {
      providers,
    },
  };
}

Screenshots / Logs 📽

[next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error invalid json response body at http://localhost:3000/api/auth/providers reason: Unexpected token < in JSON at position 0 {
  error: {
    message: 'invalid json response body at http://localhost:3000/api/auth/providers reason: Unexpected token < in JSON at position 0',
    stack: 'FetchError: invalid json response body at http://localhost:3000/api/auth/providers reason: Unexpected token < in JSON at position 0\n' +
      '    at /Users/muratcemyalin/ReactProjects/instagram-clone/node_modules/node-fetch/lib/index.js:272:32\n' +
      '    at processTicksAndRejections (internal/process/task_queues.js:95:5)',
    name: 'FetchError'
  },
  path: 'providers',
  message: 'invalid json response body at http://localhost:3000/api/auth/providers reason: Unexpected token < in JSON at position 0'
}

Environment 🖥

System: OS: macOS 11.6 CPU: (8) x64 Apple M1 Memory: 42.23 MB / 16.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 14.18.1 - /usr/local/bin/node npm: 6.14.15 - /usr/local/bin/npm Browsers: Chrome: 96.0.4664.110 Firefox: 93.0 Safari: 15.0 npmPackages: next: 12.0.7 => 12.0.7 next-auth: ^4.0.6 => 4.0.6 react: 17.0.2 => 17.0.2

Contributing 🙌🏽

No, I am afraid I cannot help regarding this

balazsorban44 commented 2 years ago

I could not reproduce. Please provide a minimal reproduction.

akhfaern commented 2 years ago

i've found this question at stackoverflow who encountered same problem with me.

https://stackoverflow.com/questions/70050759/trying-to-configure-next-auth-signin-page-but-having-a-problem-with-getprovider

you can see the minimal reproduction there

but if i go to http://localhost:3000/api/auth/providers it returns

{"google":{"id":"google","name":"Google","type":"oauth","signinUrl":"http://localhost:3000/api/auth/signin/google","callbackUrl":"http://localhost:3000/api/auth/callback/google"}}

which is normal so i think there is a problem with async await in getServerSideProps

and also it works fine if i move getProviders to client side like:

const [providers, setProviders] = useState(null);

  useEffect(() => {
    (async () => {
      const res = await getProviders();
      setProviders(res);
    })();
  }, []);
balazsorban44 commented 2 years ago

Since you opened this issue, I expect a reproduction from you, not someone else's from stack overflow. Please take the time to report an issue if you would like it resolved as quickly as possible. It helps both of us.

On the stack overflow link it was also suggested that you double check your NEXTAUTH_URL value. I recommend the same.

akhfaern commented 2 years ago

here is my total 10 lines of code to reproduction: https://github.com/akhfaern/nextauth-bug-report requested url: http://localhost:3000/auth/signin

of course i checked NEXTAUTH_URL . as you didnt read my comments i said error: { message: 'invalid json response body at http://localhost:3000/api/auth/providers reason: Unexpected token < in JSON at position 0',

but when i opened in new tab http://localhost:3000/api/auth/providers it just works fine and returns json data. also when i moved getProviders to component body It just works fine too! it just doesnt work in getServerSideProps. but in nextauth documents it says it has to work. also there are lots of examples on internet that shows the same code working i guess some update broke it.

imphillipzissou commented 2 years ago

Hey folks, I was running into this issue earlier today on a new next/react project. I was using the same versions as noted above. Ultimately, I ended up stumbling upon a blog article about v4 ServerSideProps. I modified mine to use getServerSession instead of getSession and it seems to be working fine now.

import { GetServerSidePropsContext } from 'next'
import { authOptions } from "../api/auth/[...nextauth]"

export async function getServerSideProps(context:GetServerSidePropsContext) {
  const session = await getServerSession(context, authOptions)

  console.log(session);

  return {
    props: {
      session,
    },
  }
}

Best!

edit: realized this was for session and not providers; I was having the issue with both sessions and providers.

tamvo22 commented 2 years ago

Hello @akhfaern,

From your repo, I found that it's missing the following. After I add those missing items, the Google provider button shows up fine for me. You can clone the example repo and start from there if you're still having issues. https://github.com/nextauthjs/next-auth-example

_app:

import { SessionProvider } from 'next-auth/react';
import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  return (
    <SessionProvider session={pageProps.session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
}

export default MyApp;

[...nextauth].js

import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
  secret: process.env.SECRET,

  session: {
    strategy: 'jwt',
  },
  pages: {
    signIn: '/auth/signin',
    error: '/auth/signin',
  },
});
akhfaern commented 2 years ago

hello @tamvo22, i've updated the repo in according to your code samples. still not working.. still the same error. and your sample repo does not helping because it has no custom signin page and what i am stuck is making a custom sign in page with getProviders function. actully i made it work without SSR but i want to do it in getServerSideProps which doesnt work

dzerium commented 2 years ago

Experienced this same thing too. I tried containerizing the app and running it through Docker and it's all working as expected. (weird I know)