DEV Community

Cover image for Using Credentials provider with a custom backend in NextAuth.js!

Using Credentials provider with a custom backend in NextAuth.js!

Twisha on January 22, 2021

Hello! NextAuth is a great choice when it comes to adding authentication to your next.js app. And it's easy to see why, with it's vast coverage of ...
Collapse
 
hashinclude72 profile image
Shubham Jaswal

you can also set redirect = false and catch response from signIn function :

const res = await signIn('credentials',
      {
        email,
        password,
        callbackUrl: `${window.location.origin}/account_page` 
        redirect: false,
      }
    )
if (res?.error) handleError(res.error)
if (res.url) router.push(res.url);
Enter fullscreen mode Exit fullscreen mode

signIn return a Promise which has following structure :

{
    error: string || undefined,
    status: number,
    ok: boolean,
    url: url || null
}
Enter fullscreen mode Exit fullscreen mode

you can check more on next-auth.js.org/getting-started/c...

Collapse
 
twisha profile image
Twisha

Cool! Happy to see it has been added as a feature. Thanks for the update :)

Collapse
 
juandadev profile image
Juanda Martínez

Thank you so much! I hated that the function reloaded the page every time I submit the form

Collapse
 
brianwachira profile image
brianwachira

How does this work?
I have followed your example and am not getting any response in login page

Collapse
 
sawebb profile image
Austin Webb

You are not getting a response because the user isn't being set properly. The following code is able to handle Credentials (user & pass) and Providers auth, while setting jwt and session correctly.

callbacks: {
    jwt: async (token, user) => {
      if (user) {
        token.jwt = user.jwt;
        token.user = user.user;
        token.accessToken = user?.accessToken;
      }
      return Promise.resolve(token);
    },
    session: async (session, token) => {
      session.jwt = token.jwt;
      session.accessToken = token.accessToken ? token.accessToken :
      session.user = token.user ? token.user : session.user; 
      return Promise.resolve(session);
    },
},
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dededavida profile image
David Cruz • Edited

Hi guys, if you need the token in an axios request, do it like this!

api.tsx

Collapse
 
mnengwa profile image
mnengwa

Hi guys, the article has gotten me as far as a successful authentication, for which am grateful. However, I am unable to get the session data using getSession() or useSession() client-side for which they both return null. What are the possible causes of the bug/issue?

Collapse
 
twisha profile image
Twisha • Edited

Have you added the Provider in your _app.js ?

import { Provider } from 'next-auth/client'

export default function App ({ Component, pageProps }) {
  return (
    <Provider session={pageProps.session}>
      <Component {...pageProps} />
    </Provider>
  )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hrghafoori profile image
HamidReza Ghafoori

for me it returns undefined.
Did you solve your problem? If yes, can you explain me how?

Collapse
 
lucastech profile image
Lucas

I would be interested in the HTML parts as well! do you have a zip of the shell project? I'm new to building React and Next applications from the ground up and find that most tutorials omit important details, making it very difficult to figure out what they are

Collapse
 
twisha profile image
Twisha

Sure thing. I'll add the HTML part soon

Collapse
 
bharath_ profile image
Bharath Radhakrishnan

Hello Twisha, I came here after one full days googling. I wanted to create a social media sign up button for a nextjs app with with what you call a custom laravel backend. The usage of ' pages/api/[..nextauth].js ' made me asking, where are they even using the custom backend .
So Just to confirm, even you have a custom backend you have to use pages/api feature in the app and define your auth providers there and call the custom backend api's from there right ?

Collapse
 
twisha profile image
Twisha

Hey Bharath,

If you are using a third party provider for authentication i.e Google, Facebook, Apple, Twitter etc. you don't need a custom backend as everything will be handled by nextauth.js.

If instead you want to use email-passsword login where the credentials are sent to your custom backend (in this case I'm assuming your Laravel app) then you can use the Credentials provider and configure it as it is explained in the article.

For third party provider logins (google, facebook, twitter etc.) nextauth has good documentation. For example this one is for Google -> next-auth.js.org/providers/google

Overall all the configurations for next-auth is in the pages/api/[..nextauth].js file.

Hope it answers your question :)

Collapse
 
bharath_ profile image
Bharath Radhakrishnan

What I actually wanted was to save the username, email ... fields after the google / signup to my own database. I think I figured it out. I am using the callbacks options inside the [...nextauth].js to call my api to pass username and email to my backend to store in my db.

Thread Thread
 
twisha profile image
Twisha

Ah okay I see what you mean, thanks for sharing your solution :)

Collapse
 
shadeemerhi profile image
Shadee Merhi

Hi there! Thank you for this very helpful article. I understand the login process, but how would you go about creating a custom registration page? Would you have to use the same 'authorize' callback that would have to hit different API endpoints (/login, /signup)? I would love to hear your thoughts on this :)

Collapse
 
brhanegiday profile image
Brhane Giday

Please find this link.
dev.to/ekrresa/authenticating-with...

Collapse
 
elissonmichael profile image
Élisson Michael

Thanks for sharing this.

Collapse
 
twisha profile image
Twisha

Glad it helped! :)

Collapse
 
vladilie profile image
Vlad Ilie

Hi Twisha! Great article, thanks for the tips!

I'm wondering if there is a possibility to implement a OTP Login with NextAuth. I can't find anything on the internet 🤔 Do you have some advices?

Thank you! 🎩

Collapse
 
twisha profile image
Twisha

Thanks Vlăduț Ilie !

Unfortunately I have not explored that option with NextAuth yet :(

Hope you find a useful solution soon :)

Collapse
 
danisimba profile image
Dani

Muy útil ... mucha gracias!

Collapse
 
twisha profile image
Twisha

Glad it's helpful :)

Collapse
 
mnengwa profile image
mnengwa

Hi Twisha, nice article. However the file to configure the providers should be pages/api/auth/[...nextauth].js NOT pages/api/auth/[...next-auth].js

Collapse
 
twisha profile image
Twisha

That's correct! Thanks for catching that. Will update the article

Collapse
 
agungmandala profile image
Agung Mandala Putra

Should we use session table in database for post our session?

Collapse
 
nanu146 profile image
Bharadwaj Kopparthi

this does not handle CSRF token. Could you please share how you would go about handling cross site request forgery?

Collapse
 
caiogrossi profile image
Caio Grossi

THANK YOU SO MUCH !

Collapse
 
twisha profile image
Twisha

Glad it helped! :)

Collapse
 
senorlobito profile image
senor_lobito

You just absolutely saved me! First article I found which is dealing with own backend. 1000x thanks @twisha !

Collapse
 
twisha profile image
Twisha

I'm so glad! :)

Collapse
 
jpbp profile image
João Pedrozo

In the JWT callback you access the token inside user.data, isn't that not secure?

Collapse
 
nosnart profile image
Son Tran

Can you share the source code of this article

Collapse
 
twisha profile image
Twisha • Edited

Yup I have updated the article with a link!

Collapse
 
thetymtravellr profile image
Robiul Hasan

This is great. but can you give me idea how to to that with sanity cms?