OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'User') in NextJs

  • Thread starter Thread starter Sarfaraz Unar
  • Start date Start date
S

Sarfaraz Unar

Guest
Hi Developers hope you will fine and doing well. I was working on a simple website called Techryzer that is simple web development company website where i was practicing to create website with NextJs. From Yesterday i am getting error from NextJs enter image description here This error is not displaying when i visit other routes but when I visit http://localhost:3000/dashboard/user/projects/new route. I am using Usermodel.js in that folder nor any APIs related to user model. I have tried to get help from ChatGPT, Gemini & Meta AI but failed to solve this error.

Here is complete code on github: https://github.com/sarfarazunarr/techryzer

Snippet of Prform.js (Component used on projects/new)

Code:
"use client";
import { getUserSession } from '../../../../../lib/utils';
import React, { useEffect, useState } from 'react'
import { connectDB } from '../../../../../lib/db_connection';

function Prform() {
    const [pending, setPending] = useState(false);
    const [userid, setUserid] = useState();
    const [message, setMessage] = useState('');
    const [data, setData] = useState({
      title: '',
      category: '',
      description: '',
      clientName: getUserSession()?.name || '',
      budget: 0,
      deadline: '',
    });
    useEffect(() => {
        const fetchData = async () => {
        await connectDB();
          const sessiondata = await getUserSession();
          setUserid(sessiondata?.id || '');
          setData({
            title: '',
            category: '',
            description: '',
            clientName: sessiondata?.name || '',
            budget: 0,
            deadline: '',
          });
        };
        fetchData();
      }, []);
    const handleSubmit = () => {
        setPending(true)
        try {
            console.log(data, userid)
            setMessage('Data Recieved')
            setPending(false)
            
        } catch (error) {
            setPending(false)
            setMessage('Error')
            console.log(error)
        }
    }

    const onChange = (e) => {
        setData({
            ...data,
            [e.target.id]: e.target.value
        })
    }
    return (...

usermodel.js

Code:
import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';

const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  phone: { type: String, required: true },
  registration_date: { type: Date, default: Date.now },
  account_type: { type: String, enum: ['client', 'partner', 'admin'], default: 'client' },
  password: { type: String, required: true },
  isVerified: { type: Boolean, default: false }
});

// Middleware to hash the password before saving
userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();

  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error) {
    next(error);
  }
});

// Method to validate password
userSchema.methods.validatePassword = async function(password) {
  return await bcrypt.compare(password, this.password);
};

const User = mongoose.models.User || mongoose.model('User', userSchema);

export default User;

dbConnection.js and utils

Code:
import mongoose from "mongoose";
const connectString = process.env.MONGOURI
export async function connectDB() {
  if (mongoose.connections[0].readyState) return;

  try {
    await mongoose.connect(connectString);
    console.log("MongoDB connected successfully!");
  } catch (error) {
    console.error("Error connecting to MongoDB:", error);
  }

  return true;
}

//utils
const { authOptions } = require("../app/api/auth/[...nextauth]/route");
const { getServerSession } = require("next-auth");
const base = process.env.BASE_URL;

export const getUserSession = async () => {
    const session = await getServerSession(authOptions)
    const sessionJSON = JSON.stringify(session, null, 2);
    const sessionData = JSON.parse(sessionJSON);
    const type = sessionData.user.account_type;
    const name = sessionData.user.name;
    const email = sessionData.user.email;
    const id = sessionData.user.id;
    const data = {name, email, id, type};
    return data;
}

export async function fetchApiData(path) {
    const base = process.env.BASE_URL
    const res = await fetch(base + path)
    const data = await res.json()
    return data;
  }

Please help me!

I have checked all routes and changed my prform.js which async before to non-async component and imported all hooks, functions, updated nextjs version from 14.2.3 to 14.2.4.

<p>Hi Developers hope you will fine and doing well.
I was working on a simple website called Techryzer that is simple web development company website where i was practicing to create website with NextJs.
From Yesterday i am getting error from NextJs
<a href="https://i.sstatic.net/82w8f28T.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/82w8f28T.png" alt="enter image description here" /></a>
This error is not displaying when i visit other routes but when I visit <code>http://localhost:3000/dashboard/user/projects/new</code> route. I am using Usermodel.js in that folder nor any APIs related to user model. I have tried to get help from ChatGPT, Gemini & Meta AI but failed to solve this error.</p>
<p>Here is complete code on github: <a href="https://github.com/sarfarazunarr/techryzer" rel="nofollow noreferrer">https://github.com/sarfarazunarr/techryzer</a></p>
<p>Snippet of Prform.js (Component used on projects/new)</p>
<pre><code>"use client";
import { getUserSession } from '../../../../../lib/utils';
import React, { useEffect, useState } from 'react'
import { connectDB } from '../../../../../lib/db_connection';

function Prform() {
const [pending, setPending] = useState(false);
const [userid, setUserid] = useState();
const [message, setMessage] = useState('');
const [data, setData] = useState({
title: '',
category: '',
description: '',
clientName: getUserSession()?.name || '',
budget: 0,
deadline: '',
});
useEffect(() => {
const fetchData = async () => {
await connectDB();
const sessiondata = await getUserSession();
setUserid(sessiondata?.id || '');
setData({
title: '',
category: '',
description: '',
clientName: sessiondata?.name || '',
budget: 0,
deadline: '',
});
};
fetchData();
}, []);
const handleSubmit = () => {
setPending(true)
try {
console.log(data, userid)
setMessage('Data Recieved')
setPending(false)

} catch (error) {
setPending(false)
setMessage('Error')
console.log(error)
}
}

const onChange = (e) => {
setData({
...data,
[e.target.id]: e.target.value
})
}
return (...
</code></pre>
<p>usermodel.js</p>
<pre><code>import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';

const Schema = mongoose.Schema;

const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
phone: { type: String, required: true },
registration_date: { type: Date, default: Date.now },
account_type: { type: String, enum: ['client', 'partner', 'admin'], default: 'client' },
password: { type: String, required: true },
isVerified: { type: Boolean, default: false }
});

// Middleware to hash the password before saving
userSchema.pre('save', async function(next) {
if (!this.isModified('password')) return next();

try {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
next();
} catch (error) {
next(error);
}
});

// Method to validate password
userSchema.methods.validatePassword = async function(password) {
return await bcrypt.compare(password, this.password);
};

const User = mongoose.models.User || mongoose.model('User', userSchema);

export default User;

</code></pre>
<p>dbConnection.js and utils</p>
<pre><code>import mongoose from "mongoose";
const connectString = process.env.MONGOURI
export async function connectDB() {
if (mongoose.connections[0].readyState) return;

try {
await mongoose.connect(connectString);
console.log("MongoDB connected successfully!");
} catch (error) {
console.error("Error connecting to MongoDB:", error);
}

return true;
}

//utils
const { authOptions } = require("../app/api/auth/[...nextauth]/route");
const { getServerSession } = require("next-auth");
const base = process.env.BASE_URL;

export const getUserSession = async () => {
const session = await getServerSession(authOptions)
const sessionJSON = JSON.stringify(session, null, 2);
const sessionData = JSON.parse(sessionJSON);
const type = sessionData.user.account_type;
const name = sessionData.user.name;
const email = sessionData.user.email;
const id = sessionData.user.id;
const data = {name, email, id, type};
return data;
}

export async function fetchApiData(path) {
const base = process.env.BASE_URL
const res = await fetch(base + path)
const data = await res.json()
return data;
}

</code></pre>
<p>Please help me!</p>
<p>I have checked all routes and changed my prform.js which async before to non-async component and imported all hooks, functions, updated nextjs version from 14.2.3 to 14.2.4.</p>
 

Latest posts

Top