next-auth custom signIn form don't pass username and password to [...nextauth].js

Viewed 1100

I wanna use custom signin page for next-auth

problem is that I can not pass data from signin page to [...nextauth].js .

signIn('credentials', { redirect: false, phone: phone, password: password })

can access to provider in [..nextauth].js , but

Providers.Credentials({... didn't run for getting token from API .

1.[...nextauth].js

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import axios from 'axios'
import { useRouter } from 'next/router'

const providers = [
  Providers.Credentials({
    id: 'credentials',
    name: 'credentials',
    authorize: async (credentials) => {
      const user = await axios.post('MyAPI',
        {
          phone: credentials.phone,
          password: credentials.password
        },
      )
    }
  })
]
const callbacks = {
  // Getting the JWT token from API response
  async session(session, user) {
    session.accessToken = user.token
    return session
  }
}
const options = {
  providers,
  callbacks
}

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

2.signin.js

import { useState } from "react";
import { signIn, csrfToken } from 'next-auth/client';

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

  const handleSubmit = async (e) => {
    // e.preventDefault();
    await signIn('credentials', { redirect: false, phone: phone, password: password })
  };


  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Phone</label>
        <input
          id="username"
          name="username"
          type="text"
          placeholder="Phone"
          onChange={(e) => setPhone(e.target.value)}
          value={phone}
        />
      </div>
      <div>
        <label>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>
  );
}

1 Answers

in your [...nextauth].js, you need to specify the credentials:

...
credentials: {
 username: { label: "Username", type: "text" },
 password: {  label: "Password", type: "password" }
}
...

Follow the docs https://next-auth.js.org/providers/credentials


A suggestion:
if your backend is self-hosted, why not to query your db directly as [...nextauth].js runs on the backend?

Related