Next.js Discord

Discord Forum

gegtServerSession can't read my MongoDB URI in env

Answered
Clytax posted this in #help-forum
Open in Discord
Avatar
I am trying to get my current Session in side a getServerSideProps like this:
export async function getServerSideProps(context: any) {
  const session = await getServerSession(authOptions);

  
  return {
    props: { session },
  };
}


and this is my authOptions file.
export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      id: "credentials",
      credentials: {
        email: { label: "Email", type: "text", placeholder: "jsmith" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        await connectDB();
        const userFound = await User.findOne({
          email: credentials?.email,
        }).select("+password");

        if (!userFound) throw new Error("Ungültige Email");

        const passwordMatch = await bcrypt.compare(
          credentials!.password,
          userFound.password
        );

        if (!passwordMatch) throw new Error("Ungültiges Passwort");
        return userFound;
      },
    }),
  ],
  pages: {
    signIn: "/login",
  },
  session: {
    strategy: "jwt",
  },
  callbacks: {
    async jwt({ token, user, session, trigger }) {
      if (trigger === "update" && session?.name) {
        token.name = session.name;
      }

      if (trigger === "update" && session?.email) {
        token.email = session.email;
      }

      if (user) {
        const u = user as unknown as any;
        return {
          ...token,
          id: u.id,
          name: u.firstName,
          email: u.email,
        };
      }
      return token;
    },
    async session({ session, token }) {
      return {
        ...session,
        user: {
          ...session.user,
          _id: token.id,
          name: token.name,
          email: token.email,
        },
      };
    },
  },
};

Running this leads to these errors "Error: MONGODB_URI must be defined" multiple times. My connectDB file is this:
import mongoose from "mongoose";

const { MONGODB_URI } = process.env;

if (!MONGODB_URI) {
  throw new Error("MONGODB_URI must be defined");
}

export const connectDB = async () => {
  try {
    const { connection } = await mongoose.connect(MONGODB_URI);
    if (connection.readyState === 1) {
      console.log("MongoDB Connected");
      return Promise.resolve(true);
    }
  } catch (error) {
    console.error(error);
    return Promise.reject(error);
  }
};


Why cant it read my MONGODB_UI string?
Or is there a better way to get the session?
Answered by averydelusionalperson
example:

async function getData() {
  const res = await fetch('https://api.example.com/...')
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.
 
  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data')
  }
 
  return res.json()
}
 
export default async function Page() {
  const data = await getData()
 
  return <main></main>
}
View full answer

28 Replies

Avatar
accidentally deleted the last post, sorry for repost
Avatar
you have MONGODB_URI in .env file ?
Avatar
yea
.env.local file
Avatar
can you access it from any other file?
the MONGODB_URI
Avatar
Yea it works when I use it in my App Router for login etc.
just there when adding authOptions to getServerSession the issue comes up
Avatar
you're using pages router right?
Avatar
nope app router
Avatar
you can't do getServerSideProps in app router
directly access the session in the server component
Avatar
Ohhh so I cant prefetch data in app router?
Avatar
you can, but you don't need getServerSideProps for it, the component/page is automatically server, unless you add 'use client' directive at the top.
you can read the new docs for more information.
Avatar
example:

async function getData() {
  const res = await fetch('https://api.example.com/...')
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.
 
  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data')
  }
 
  return res.json()
}
 
export default async function Page() {
  const data = await getData()
 
  return <main></main>
}
Answer
Avatar
^ There was no need of serverSideProps, directly use the server side things in the component.
Avatar
Oh you are right, thanks alot! Had a lot of headaches yesterday because of it xD Didn't see that I can't use getServerSideProps :c
Avatar
No worries !
Consider closing the thread if your problem is solved.
^
Avatar
ahh i was just about to ask how do to that haha
Avatar
🫡
Avatar
It doesnt allow me to make the page async, if I turn the component to a server component I cant use useSession, any idea?
Alright for now it works with useEffect, I rather would have just used the funktion straight in the body of the page though
Avatar
that's the key, you need to know what component should be client, and what should be server.
anyways, if you've anymore doubts, open a new thread. Since this closed.
Avatar
alright, thanks again ^^