Next Js combined with an external REST API Authentication and atuhorization

Viewed 8740

I have already an application built with Node Js and express , also I have a front end using create-react-app with redux , but now I would like to move it to next Js, but I've got stuck because I do not the right way to authenticate and authorize using my rest Full API, I want to mention that my API already handle this using JWT (saving it within a cookie)

1 Answers

Next-Auth is a go-to in such a case. The following example shows how to get started with password authentication.

Create a file called /pages/api/auth/[...nextauth].js

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

const options = {
  providers: [
    Providers.Credentials({
    // The name to display on the sign in form (e.g. 'Sign in with...')
    name: 'Email and Password',
    credentials: {
      username: { label: "Username", type: "text", placeholder: "jsmith" },
      password: {  label: "Password", type: "password" }
    },
    authorize: async (credentials) => {
      // Add logic here to look up the user from the credentials supplied eg from db or api
      const user = { id: 1, name: 'J Smith', email: 'jsmith@example.com' }

      if (user) {
        // Any object returned will be saved in `user` property of the JWT
        return Promise.resolve(user)
      } else {
        // If you return null or false then the credentials will be rejected
        return Promise.resolve(null)
        // You can also Reject this callback with an Error or with a URL:
        // return Promise.reject(new Error('error message')) // Redirect to error page
        // return Promise.reject('/path/to/redirect')        // Redirect to a URL
      }
    }
  }),
  ],
}

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

Then on your component code:

import React from 'react'
import {
  signIn, 
  signOut,
  useSession
} from 'next-auth/client'

export default function myComponent() {
  const [ session, loading ] = useSession()

  return <>
    {!session && <>
      Not signed in <br/>
      <button onClick={signIn}>Sign in</button>
    </>}
    {session && <>
      Signed in as {session.user.email} <br/>
      <button onClick={signOut}>Sign out</button>
    </>}
  </>
}

This would easily get you started, if you shared more of the auth routes you have I can advise more.

Related