How to do authentication using NextAuth.js without login page (using postman)

Viewed 1167

So far, in my Next.js app I've done my signup.

I was asked to do authentication (login) using next-auth with custom credentials. I have to make a rest API endpoint: api/auth/login.

I know how to do this with the login page (from this NextAuth.js Credentials Provider). Can be done easily [...nextauth].js (Please have a look).

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import prisma from '../../../lib/prisma'

const options = {
    providers: [
        Providers.Credentials({
            name: 'Credentials',
            credentials: {
                email: { label: "Email", type: "email", placeholder: "something@example.com" },
                password: {  label: "Password", type: "password" }
            },
            async authorize(credentials) {
                const {email, password} = credentials
                const user = await prisma.user.findFirst({ where: { email, password } })
                console.log(user);
            
                // If no error and we have user data, return it
                if (user) {
                return user
                }
                // Return null if user data could not be retrieved
                return null
          }
        })
      ]
}

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

But, the problem is my rest API endpoint (api/auth/login) will be hit/tested using Postman. So, how can I achieve it that is the same functionality without front-end like typical rest API behavior (req-res).

I'm stuck into /pages/api/auth/login.js file:

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import prisma from '../../../lib/prisma'

const options = {
    providers: [
        Providers.Credentials({
            name: 'Credentials',
            credentials: {
                email: { label: "Email", type: "email", placeholder: "something@example.com" },
                password: {  label: "Password", type: "password" }
            },
            async authorize(credentials) {
                const {email, password} = credentials
                const user = await prisma.user.findFirst({ where: { email, password } })
                console.log(user);
            
                // If no error and we have user data, return it
                if (user) {
                return user
                }
                // Return null if user data could not be retrieved
                return null
          }
        })
      ]
}

export default async function handle(req, res) {
    if (req.method === 'POST') NextAuth(req, res, options)
}

Have no idea how do I achieve this in a rest API way.

I've tried an way: Please have a look API resolved without sending a response for /api/auth/callback/credentials, this may result in stalled requests

0 Answers
Related