Skip to content

Step 10 - Better fetches

Course: NextJS (Server side) - chapter 10

For the root page, we are fetching the details of the user by hitting an HTTP endpoint in getUserDetails

import axios from "axios";
async function getUserDetails() {
try {
const response = await axios.get("http://localhost:3000/api/user")
return response.data;
} catch(e) {
console.log(e);
}
}
export default async function Home() {
const userData = await getUserDetails();
return (
<div className="flex flex-col justify-center h-screen">
<div className="flex justify-center">
<div className="border p-8 rounded">
<div>
Name: {userData?.name}
</div>
{userData?.email}
</div>
</div>
</div>
);
}

getUserDetails runs on the server. This means you’re sending a request from a server back to the server

import { PrismaClient } from "@prisma/client";
const client = new PrismaClient();
async function getUserDetails() {
try {
const user = await client.user.findFirst({});
return {
name: user?.username,
email: user?.username
}
} catch(e) {
console.log(e);
}
}
export default async function Home() {
const userData = await getUserDetails();
return (
<div className="flex flex-col justify-center h-screen">
<div className="flex justify-center">
<div className="border p-8 rounded">
<div>
Name: {userData?.name}
</div>
{userData?.email}
</div>
</div>
</div>
);
}