7. Making requests from Server Components
Lets modify the Home page we made in a previous step to make a call to this API
app/components/home.tsx
import styles from "../page.module.css";
import { redirect } from "next/navigation";
import { getSSRSession } from "../sessionUtils";
import { TryRefreshComponent } from "./tryRefreshClientComponent";
import { SessionAuthForNextJS } from "./sessionAuthForNextJS";
export async function HomePage() {
const { session, hasToken, hasInvalidClaims } = await getSSRSession();
if (!session) {
if (!hasToken) {
return redirect("/auth");
}
if (hasInvalidClaims) {
return <SessionAuthForNextJS />;
} else {
return <TryRefreshComponent />;
}
}
const userInfoResponse = await fetch('http://localhost:3000/api/user', {
headers: {
/**
* We read the access token from the session and use that as a Bearer token when
* making network requests.
*/
Authorization: 'Bearer ' + session.getAccessToken(),
},
});
let message = "";
if (userInfoResponse.status === 200) {
message = `Your user id is: ${session.getUserId()}`
} else if (userInfoResponse.status === 500) {
message = "Something went wrong"
} else if (userInfoResponse.status === 401) {
// The TryRefreshComponent will try to refresh the session
return <TryRefreshComponent />
} else if (userInfoResponse.status === 403) {
// SessionAuthForNextJS will redirect based on which claim is invalid
return <SessionAuthForNextJS />;
}
// You can use `userInfoResponse` to read the users session information
return (
<SessionAuthForNextJS>
<div>
{message}
</div>
</SessionAuthForNextJS>
);
}
We use session
returned by getSSRSession
to get the access token of the user. We can then send the access token as a header to the API. When the API calls withSession
it will try to read the access token from the headers and if a session exists it will return the information. You can use the session
object to fetch other information such as session.getUserId()
.