7

I am using Next Auth and have a standalone Node.js API running. I am using Next Auth using credentials and use axios to send the username and password to the API.

On the API side, if the username and password are correct, I set a session using express-session and save it to the database.

If the response status is 201 in Next.js I want to then add the express-session token from the API to my Next.js session.

The below code is working in that I authenticate and when I console.log session in protected pages I see the express-session token that was set on the server. This token is also stored in mongoDB. But is it correct? Is the purpose of this to protect routes on the frontend only ie: checking that there is a session in Next.js

If on the protected pages I need to make an API request, would I then check that session token against the database token for the logged in user?

And lastly, where does JWT fit in here, is this how Next.js is handling the client side auth sessions, using JWT?

    import NextAuth from "next-auth";
    import CredentialsProvider from "next-auth/providers/credentials";
    import axios from "axios";
    export default NextAuth({
      session: {
        jwt: true,
        maxAge: 30 * 24 * 60 * 60,
      },
      providers: [
        CredentialsProvider({
          async authorize(credentials) {
            try {
              const response = await axios.post(`http://localhost:8000/login`, {
                email: credentials.email,
                password: credentials.password,
              });
    
              if (response.status === 201) {
                const user = {
                  email: credentials.email,
                  accessToken: response.data.token,
                };
                return user;
              } else {
                return null;
              }
            } catch (err) {
              console.log(err.response);
            }
          },
        }),
      ],
      callbacks: {
        async jwt({ token, user }) {
          if (user) {
            token.accessToken = user.accessToken;
          }
          return token;
        },
        async session({ session, token, user }) {
          session.accessToken = token.accessToken;
          return session;
        },
      },
    });
2
  • 2
    WHat if i have multiple type authentication like facebook, google, twitter, and credentials? Commented Aug 5, 2023 at 16:14
  • @BINFASK I think you would need to store the user in a database. Create an adapter to support logic with different authentication methods. Check the following link for more information Commented Nov 28, 2023 at 18:44

2 Answers 2

4
export default NextAuth({
    providers: [
      CredentialsProvider({
        name: 'Credentials',
        credentials: {
          username: {label: 'Username', type: 'text', placeholder: '[email protected]'},
          password: {label: 'Password', type: 'password', placeholder: 'password'},
        },
        async authorize({username, password}, _req) {
          try {
            const {data, error} = await fetch("<your-remote-api>")
            if (!data?.user || error) {
              return null
            }
            return data.user
          } catch (error) {
            return error
          }
        },
      }),
    ],
    callbacks: {
      jwt: async ({token, user}) => {
        if (user) {
          token.data = user
        }
        return token
      },
      session: async ({session, token}) => {
        if (token.data) {
          session.user = token.data
        }
        return session
      },
    },
  })
Sign up to request clarification or add additional context in comments.

Comments

0

If on the protected pages I need to make an API request, would I then check that session token against the database token for the logged in user?

Yes you need to check that session but from what I undesrtand, the check of the session would be to just verify the token.. so no need to query your database.

And lastly, where does JWT fit in here, is this how Next.js is handling the client side auth sessions, using JWT?

That verification is done trough JWT.. basically JWT will make sure the token you are sending is the same it has created

Note: the only thing that I don't undesrtand yet is about role permission. JWT token can tell you if the user is authenticated. But if you update user role from a dashboard admin panel, let say from active to inactive, then at some point in your api you would need to request your db to check user's role. I don't think we can rely on the token in this case

1 Comment

You can use the session callback to update your user or session data. Nextauth calls the session callback everytime the sessión needs to be updated (page refresh or tab change). Check the following link to dive in

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.