Home > Enterprise >  Getting an single user using server side props nextjs
Getting an single user using server side props nextjs

Time:11-22

I'm using nextjs to create a dashboard and I have the authentication using next-auth.

However, I'm trying to render the individual users data when they login to the dashboard but not sure where I'm going wrong, I know I have to use the findOne callback but for some reason I can't grab the ID or email.

Here is what I have so far

import { connectToDatabase } from '../../lib/mongodb';
import Head from 'next/head';
import Sidebar from '../components/Sidebar';

export default function Dashboard({ user }) {
  return (
    <>
      <Head>
        <title>Ellis Development - Dashboard</title>
      </Head>

      <Sidebar />

      <section className="content dashboard-content">
        <h1>Dashboard</h1>

        { users.map(user => (
          <div key={user.id}>
            <h2>{user.firstname} {user.lastname}</h2>
            <p>{user.email}</p>
          </div>
        )) }
      </section>
    </>
  )
}

// get data from database using server side rendering and mongodb connection
export async function getServerSideProps() {
  const client = await connectToDatabase();
  const users = await client.db().collection('users').findOne({ _id: id }).toArray();

  return {
    props: {
      users: JSON.parse(JSON.stringify(users))
    }
  }
}

CodePudding user response:

You can use getSession to handle server-side authentications.

check reference for more resources link

import { getSession } from "next-auth/react"
...
export async function getServerSideProps(ctx) {
  const session = await getSession(ctx) //pass context to authenticate create session
  const id = session.user.id //get id from session

  const client = await connectToDatabase();
  const user = await client.db().collection('users').findOne({ _id: id }) // No need to use toArray its returns only 1 object

  return {
    props: {
      user
    }
  }
}
  • Related