postgresqlnext.jssequelize.js

While trying to login into my Next.js app, getting 500 error, Import trace for requested module


I have setup my Next.js web application in my local system. While trying to login into app, I am getting following error, ie login request POST http://localhost:3000/api/login 500 (Internal Server Error).

Sharing detailed error details logged in terminal below :

 ⚠ ./node_modules/sequelize/lib/dialects/abstract/connection-manager.js
Critical dependency: the request of a dependency is an expression

Import trace for requested module:
./node_modules/sequelize/lib/dialects/abstract/connection-manager.js
./node_modules/sequelize/lib/dialects/mariadb/connection-manager.js
./node_modules/sequelize/lib/dialects/mariadb/index.js
./node_modules/sequelize/lib/sequelize.js
./node_modules/sequelize/lib/index.js
./node_modules/sequelize/lib/index.mjs
./app/utility/db.js
./app/api/login/route.js
 ⚠ ./node_modules/sequelize/lib/dialects/abstract/connection-manager.js
enter code here

I have my postgres database is up and running and the user table has the user details. Could someone please advise what could be the issue here:

Version dependencies:

"dependencies": {
    "axios": "^1.7.2",
    "bcryptjs": "^2.4.3",
    "next": "14.2.5",
    "pg": "^8.12.0",
    "pg-hstore": "^2.3.4",
    "postgres": "^3.4.4",
    "react": "^18",
    "react-dom": "^18",
    "sequelize": "^6.37.3"
  },

// app/api/login/route.js

import { sequelize, user } from '../../utility/db';
import { NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';


export async function GET(req) {
  return NextResponse.json({ message: 'GET request received' });
}


export async function post(req) {
  const { email, password } = await req.json();
  
  try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');

    const foundUser = await user.findOne({ where: { email } });
    if (!foundUser) {
      return NextResponse.json({ message: 'Invalid email or password' }, { status: 401 });
    }

    const passwordMatch = await bcrypt.compare(password, foundUser.password);
    if (!passwordMatch) {
      return NextResponse.json({ message: 'Invalid email or password' }, { status: 401 });
    }

    return NextResponse.json({ message: 'Login successful' });
  } catch (error) {
    console.error('Unable to connect to the database:', error);
    return NextResponse.json({ message: 'Internal server error' }, { status: 500 });
  }
}

db.js

import { Sequelize, DataTypes } from 'sequelize';

const DB_POOL = {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
const sequelize = new Sequelize('clubdb', 'postgres', 'password_here', {
    host: 'localhost',
    dialect: 'postgres', // or 'postgres' if you're using PostgreSQL
    port: '5432',
  });
  
  const user = sequelize.define('user', {
      id: {
          type: DataTypes.INTEGER(10),
          allowNull: false,
          primaryKey: true,
          autoIncrement: true
      },
      email: {
          type: DataTypes.STRING,
          allowNull: false,
          unique: true
      },
      password: {
          type: DataTypes.STRING,
          allowNull: false
      }
  }, {
      timestamps: true,
      tableName: 'user'
  });

// Export the sequelize instance and models
export { sequelize, user };

app/login/page.js

'use client';
import { useState } from 'react';
import axios from 'axios';
import { useRouter } from 'next/navigation'; // Correct import
import { useAuth } from '../contexts/authContext';

  const Login = () =>{
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const router = useRouter();
  const { dispatch } = useAuth();

  const handleLogin = async (e) => {
    e.preventDefault();

    try {
      const response = await axios.post('/api/login/', { email, password });
      if (response.status === 200) {
        localStorage.setItem('isAuthenticated', 'true');
        dispatch({ type: 'LOGIN' });
        router.push('/admin');
      }
    } catch (error) {
      setError(error.response?.data?.message || 'Login failed');
    }
    
  };

    return (
        <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
          <h1 className="text-4xl font-bold">Login</h1>
          <form onSubmit={handleLogin} className="mt-4">
            <input
              type="text"
              placeholder="Username"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="border p-2 rounded mb-4"
            />
            <input
              type="password"
              placeholder="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="border p-2 rounded mb-4"
            />
            {error && <p className="text-red-500">{error}</p>}
            <button type="submit" className="bg-blue-500 text-white p-2 rounded">
              Login
            </button>
          </form>
        </div>
      );

  }
  export default Login;

_app.js

import '../styles/globals.css';
import Navbar from './components/navbar';
import { AuthProvider } from './contexts/authContext';

const MyApp = ({ Component, pageProps }) => {
  console.log('Rendering MyApp');

    return (
        <>
        <AuthProvider>
          <Navbar />
          <Component {...pageProps} />
        </AuthProvider>
          
        </>
      );
}

export default MyApp;

Folder structure:

app
│
├── about
│   └── page.js
│
├── admin
│   └── page.js
│
├── api\login
│         └── route.js
│
├── components
│   └── navbar.js
│
├── contexts
│   └── authContext.js
│
├── login
│   └── page.js
│
├── styles
│   └── globals.css
│
├── utility
│   └── db.js
│
└── _app.js
favicon.ico
layout.js
page.js

Solution

  • Now the error has gone and able to login into the system, after I have separated sequelize.js and User.js. Then I have used DATABASE_URL and dialectModule: pg in the below connection.

    /* utility/sequelize.js */

           import * as pg from 'pg';
           import { Sequelize } from 'sequelize';
        
            const DATABASE_URL = 'postgres://username:password@localhost:5432/database_name';
            const sequelize = new Sequelize(DATABASE_URL, {
              dialectModule: pg
            });
    
        (async () => {
           try {
           await sequelize.authenticate();
           console.log('Database connection successfully established.');
          } catch (error) {
            console.error('Error connecting to the database :', error);
          }
         })();
         export default sequelize;
    

    /* models/User.js */

    import { DataTypes } from 'sequelize';
    import sequelize from '../utility/sequelize';
    
      const user = sequelize.define('user', {
          id: {
              type: DataTypes.INTEGER(10),
              allowNull: false,
              primaryKey: true,
              autoIncrement: true
          },
          email: {
              type: DataTypes.STRING,
              allowNull: false,
              unique: true
          },
          password: {
              type: DataTypes.STRING,
              allowNull: false
          }
      }, {
          timestamps: true,
          tableName: 'user'
      });
    
      export default user;