最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I fix an internal server error when authenticating with Next-Auth? - Stack Overflow

programmeradmin2浏览0评论

I am trying to add authentication to my Next.js project with Next-Auth. However, I am stuck on a 500 internal server error after submitting credentials (http://localhost:3000/api/auth/error?error=Configuration).

I think it might be something to do with running on http://localhost:3000, but I'm not sure. What I'm doing wrong?

pages/api/auth/[...nextauth].js

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';

const options = {
  site: 'http://localhost:3000',

  providers: [
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        username: { label: 'Username', type: 'text', placeholder: 'jsmith' },
        password: { label: 'Password', type: 'password' },
      },
      authorize: async (credentials) => {
        consol.log('credentials', credentials);
        const user = { id: 1, name: 'J Smith', email: '[email protected]' };
        if (user) {
          return Promise.resolve(user);
        } else {
          return Promise.resolve(null);
        }
      },
    }),
  ],
  database: process.env.MONGO_URI,
};

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

pages/index.js

import { useSession } from 'next-auth/client';

export default function Home() {
  const [session, loading] = useSession();
  console.log('session', session);

  return (
    <div className="container">
      <main>
          {session && <p>Signed in as {session.user.email}</p>}
          {!session && (
            <p>
              <a href="/api/auth/signin">Sign in</a>
            </p>
          )}
      </main>
    </div>
  );
}

pages/_app.js

import { Provider } from 'next-auth/client';
import '../styles.css';

export default ({ Component, pageProps }) => {
  const { session } = pageProps;
  return (
    <Provider options={{ site: process.env.SITE }} session={session}>
      <Component {...pageProps} />
    </Provider>
  );
};

next.config.js

module.exports = {
  env: {
    MONGO_URI: '...',
    SITE: 'http://localhost:3000',
  },
};

I am trying to add authentication to my Next.js project with Next-Auth. However, I am stuck on a 500 internal server error after submitting credentials (http://localhost:3000/api/auth/error?error=Configuration).

I think it might be something to do with running on http://localhost:3000, but I'm not sure. What I'm doing wrong?

pages/api/auth/[...nextauth].js

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';

const options = {
  site: 'http://localhost:3000',

  providers: [
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        username: { label: 'Username', type: 'text', placeholder: 'jsmith' },
        password: { label: 'Password', type: 'password' },
      },
      authorize: async (credentials) => {
        consol.log('credentials', credentials);
        const user = { id: 1, name: 'J Smith', email: '[email protected]' };
        if (user) {
          return Promise.resolve(user);
        } else {
          return Promise.resolve(null);
        }
      },
    }),
  ],
  database: process.env.MONGO_URI,
};

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

pages/index.js

import { useSession } from 'next-auth/client';

export default function Home() {
  const [session, loading] = useSession();
  console.log('session', session);

  return (
    <div className="container">
      <main>
          {session && <p>Signed in as {session.user.email}</p>}
          {!session && (
            <p>
              <a href="/api/auth/signin">Sign in</a>
            </p>
          )}
      </main>
    </div>
  );
}

pages/_app.js

import { Provider } from 'next-auth/client';
import '../styles.css';

export default ({ Component, pageProps }) => {
  const { session } = pageProps;
  return (
    <Provider options={{ site: process.env.SITE }} session={session}>
      <Component {...pageProps} />
    </Provider>
  );
};

next.config.js

module.exports = {
  env: {
    MONGO_URI: '...',
    SITE: 'http://localhost:3000',
  },
};
Share Improve this question edited Nov 8, 2023 at 21:25 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Jul 16, 2020 at 14:37 Thomas AllenThomas Allen 8118 gold badges18 silver badges33 bronze badges 4
  • 4 Philip Loosemore pointed out in an answer that there is a typo in the first section of code where console.log is written consol.log. They indicate that this typo could cause the error you are seeing. – Jason Aller Commented Jul 18, 2020 at 3:51
  • Did you find what the problem was? Thanks – Pingolin Commented Dec 16, 2020 at 20:43
  • 1 @Armel I honestly cant remember, it was a fair while ago. I think it may have been an issue with JWT (or the fact i wasn't using one!). Or could be the consol.log issue Jason mentioned above – Thomas Allen Commented Dec 17, 2020 at 12:13
  • No worries @ThomasAllen, thanks :) – Pingolin Commented Dec 17, 2020 at 13:33
Add a comment  | 

4 Answers 4

Reset to default 6

In your pages/api/auth/[...nextauth].js file, add:

secret:process.env.SECRET

SECRET must be any string value like this:

SECRET:LlKq6ZtYbr+hTC073mAmAh9/h2HwMfsFo4hrfCx6gts=

Also, add it in your Vercel environment. that’s it; your problem will be solved.

As mentioned by Dinesh, my problem was solved by adding a NEXTAUTH_SECRET to both Vercel environment variables and to [...nextauth].ts.

A local deployment worked without that variable, but Vercel deployment needed the secret. In addition to adding the Vercel environment variable, my working [...nextauth].ts looks like:

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
  callbacks: {
    async jwt({ token }) {
      token.userRole = "user"
      return token
    },
  },
})

Keep in mind NEXTAUTH_URL to be set for yourwebsite.com

process.env.NEXTAUTH_URL=https://yourwebsite.com

You had a typo under your asyc function consol.log('credentials', credentials);

Fix to console.log('credentials', credentials); and that should solve the problem.

I faced a similar problem and it was because I didn't add any providers array.

In the future, fix any typos or errors within your [...nextauth].js to fix 500 error

发布评论

评论列表(0)

  1. 暂无评论