1

I want to do react app on next.js app. I want do this on next.js app. But I don't have any current idea. Please help me to solve this. I use user authentication on backend node.js + passport.js + passport-local-mongoose + express.session. On react app use context API for store user data.

import { createContext, useCallback, useEffect, useState } from 'react';
import { Spin, message } from 'antd';
import axios from 'axios';
const url = process.env.REACT_APP_SERVER;
export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    const getUser = async () => {
      const endPoint = `${url}/v1/users/auth`;
      await axios({
        method: 'GET',
        url: endPoint,
        withCredentials: true,
      })
        .then((res) => {
          const { data } = res;
          setUser(data);
        })
        .catch((err) => {})
        .finally(() => {
          setLoading(false);
        });
    };
    getUser();
  }, []);

  return (
    <AuthContext.Provider value={{ user, setUser }}>
      {loading ? (
        <div className='tmtube-global flexCenter'>
          <Spin size='large' />
        </div>
      ) : (
        children
      )}
    </AuthContext.Provider>
  );
};

1 Answer 1

1

Update

Using NextAuth.js with a Custom Provider and Custom Database

NextAuth.js allows you to create custom authentication providers and use a custom database to store user data. Just make sure you are doing all these steps.

  • install NextAuth.js: npm install next-auth
  • Create a Custom Provider: Create a custom authentication provider with app (next.js 13) at this directory app/api/auth/[...nextauth]/route.js.

and this file should be like this:

import { NextApiRequest, NextApiResponse } from 'next'
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

export default NextAuth({
  providers: [
    Providers.Credentials({
      // The name to display on the sign-in form (e.g., "Sign in with...")
      name: 'Custom Credentials',
      credentials: {
        username: { label: "Username", type: "text" },
        password: {  label: "Password",  type: "password" }
      },
      authorize: async (credentials) => {
        // Your custom authentication logic here
        // You can query your user data directly to db here. It is safe.
        const user = { id: 1, name: "John Doe" }; // Replace with your user data logic

        if (user) {
          return user;
        } else {
          // if user not found or logic not accepted.
          return null
        }
      },
    }),
  ],
  session: {
    jwt: true,
  },
  callbacks: {
    async jwt(token, user) {
      if (user) {
        token.id = user.id;
        token.name = user.name;
      }
      return token;
    },
  },
  pages: {
    signIn: '/auth/signin', // your custom page
  },
  callbacks: {
    async session(session, token) {
      // if you need to add more info in session
      session.user.id = token.id;
      session.user.name = token.name;
      return session;
    },
  },
});

  • Usage in Your Application:

You can now use your custom authentication provider in your Next.js components. Here's an example of a login form:

// app/auth/signin.js (this our page)
import { signIn } from 'next-auth/react' // login the user

export default function SignIn() {
  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const credentials = {
      username: formData.get('username'),
      password: formData.get('password'),
    };

    const result = await signIn('credentials', { ...credentials, redirect: false });

    if (!result.error) {
      // Successfully logged in
      // Redirect or perform any necessary actions
    } else {
      // Handle authentication error
      console.error(result.error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="username" placeholder="Username" />
      <input type="password" name="password" placeholder="Password" />
      <button type="submit">Sign In</button>
    </form>
  );
}
  • Finally If you wanna get user data you can simply:
// any component file
import { useSession } from 'next-auth/react'

export default function Component({}) {
  const { status, data } = useSession()
  return (
    <div>
      {status === 'loading' ? (
        <>Loading ...</>
      ) : status === 'unauthenticated' ? (
        <>No User Logged In</>
      ) : (
        <span>
          There is authenticated user <br />
          {data?.user.username}
        </span>
      )}
    </div>
  )
}

That is it. Let me know if you need more help. Happy Coding!

Sign up to request clarification or add additional context in comments.

3 Comments

I am try use it but cannot do. How to do this using this?
or how to config next auth provider with auth via backend
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.