Cannot POST /api/auth/callback/credentials

See original GitHub issue

Your question Cannot POST /api/auth/callback/credentials

What are you trying to do Whenever I try to log in, I get the post error.

Feedback Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.

  • Found the documentation helpful
  • Found documentation but was incomplete
  • Could not find relevant documentation
  • Found the example project helpful
  • Did not find the example project helpful
<form method='post' action='/api/auth/callback/credentials' className="account-form">

For example, when I try to get the csrf token, it works fine.

NextAuth config:

const options = {
    site: 'http://localhost:3000/api/auth',
    providers: [
        Providers.Credentials({
            name: 'Credentials',
            credentials: {
                username: { label: "Username", type: "text", placeholder: "" },
                password: {  label: "Password", type: "password" }
            },
            authorize: async (credentials) => {
                const user = { id: 1, name: 'J Smith', email: 'jsmith@example.com' }

                if (user) {
                    return Promise.resolve(user)
                } else {
                    return Promise.resolve(null)
                }
            }
        })
    ],
    callbacks: {
        signIn: async (user, account, profile) => {
            return Promise.resolve(true)
        },
        session: async (session, user) => {
            session.foo = 'bar' // Add property to session
            return Promise.resolve(session)
        },
        credentials: async( user,acount,profile) => {
          return Promise.resolve(true)
        },
        redirect: async (url, baseUrl) => {
            return url.startsWith(baseUrl)
                ? Promise.resolve(url)
                : Promise.resolve(baseUrl)
        }
    },
    session: {
        jwt: true,
    },
    jwt: {
        secret: "secret",
        encryption: true
    },
    database: {
        type: 'mysql',
        host: process.env.DB_HOST,
        port: 3306,
        username: process.env.DB_USER,
        password: process.env.DB_PASS,
        database: process.env.DB_TABLE
    },
    debug: true,
}

I tried everything, and also the documentation doesn’t help since I can’t find what I’m looking for particularly.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:4
  • Comments:13 (2 by maintainers)

github_iconTop GitHub Comments

13reactions
kyrelldixoncommented, Sep 7, 2020

I was having the same issue, but I found a solution today. Here are the general steps I took:

  1. Add an id property to the Credential provider
  2. Use signIn in my form instead of action and method

Example pages/api/[...nextAuth].js

const options = {
  // Configure one or more authentication providers
  providers: [
    Providers.Credentials({
      id: "username-login", // <- add this line
      name: "Login",
      authorize: async (credentials) => {
        const user = {};
        return Promise.resolve(user);
      },
      credentials: {
        username: { label: "Username", type: "text ", placeholder: "username" },
        password: {
          label: "Password",
          type: "password",
          placeholder: "a-really-long-password",
        },
      },
    }),
  ],
  pages: {
    signIn: "/login",
  },
};

Then in pages/login.js:

import { useState } from "react";
import Layout from "@components/layout";
import { signIn, getSession } from "next-auth/client";

export default function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    // "username-login" matches the id for the credential
    signIn("username-login", { username, password });
  };

  return (
        <form onSubmit={handleSubmit}>
          <div>
            <label htmlFor="username">Username</label>
            <input
              id="username"
              name="username"
              type="text"
              placeholder="Username"
              onChange={(e) => setUsername(e.target.value)}
              value={username}
            />
          </div>
          <div>
            <label htmlFor="password">Password</label>
            <input
              id="password"
              name="password"
              type="password"
              placeholder="Password"
              onChange={(e) => setPassword(e.target.value)}
              value={password}
            />
          </div>
          <button type="submit">
            Login
          </button>
        </form>
  );
}
10reactions
kobuchin1commented, Oct 21, 2020

I’m using a custom express server with next-auth. It works now.

1. add route for post method and hand it to next.js

// server.js
       :
  const nextApp = next({ dev });
  const handle = nextApp.getRequestHandler();
       :
  app.get('*', (req, res) => {
    return handle(req, res);
  });
  // ↓↓↓ add route for post method
  app.post('*', (req, res) => {
    return handle(req, res);
  });
  // ↑↑↑ add route for post method
       :

2. set jwt: true

// /pages/api/auth/[...nextauth].js
         :
  session: {
    // ↓↓↓ add 
    jwt: true,
    // ↑↑↑ add
  },
         :

3. set bodyParser: false

// /pages/api/auth/[...nextauth].js
         :
// ↓↓↓ add config export
export const config = {
  api: {
    bodyParser: false,
  },
}
// ↑↑↑ add config export
export default (req, res) => NextAuth(req, res, options)

because I already use bodyParser on express.

// server.js
       :
  app.use(bodyParser.urlencoded({extended: true}));
  app.use(bodyParser.json());
       :
Read more comments on GitHub >

github_iconTop Results From Across the Web

Next-Auth signIn with Credentials is not working in NextJS
The issue I'm facing goes like this: I want to Login to my Next.js app using Email & Password submitted to my API...
Read more >
Callbacks | NextAuth.js
This callback is called whenever a JSON Web Token is created (i.e. at sign in) or updated (i.e whenever a session is accessed...
Read more >
error: callback for provider type credentials not supported
Error: HTTP POST is not supported for /api/auth/callback/credentials. Using Credentials Sign in provider. Open side panel.
Read more >
Sign In With Google JavaScript API reference | Authentication
callback, The JavaScript function that handles ID tokens. ... The ID token credential response is posted to your login endpoint when a user...
Read more >
Cannot GET /auth/google/callback | PassportJs - Reddit
initialize()); app.use(passport.session()); app.use(cors({ origin: "http://localhost:3000", methods: "GET,POST,PUT,DELETE", credentials: true,}) ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found