Current User not found when fetching from server
Answered
Japanese common catfish posted this in #help-forum
Japanese common catfishOP
API route:
export async function GET(req: Request) {
try {
const currentUser = await getCurrentUser();
console.log(currentUser);
if (!currentUser) {
return Response.json({ error: "Acesso não autorizado" }, { status: 401 });
}
const list = await prisma.event.findMany({
where: {
userId: currentUser.id,
},
});
return Response.json(list);
} catch (e: any) {
if (e instanceof ZodError) {
return Response.json(
{ errors: SimplifyErrors(e.errors) },
{ status: 400 }
);
}
console.log("[ERROR] POST - /api/events");
console.log(e);
return Response.json(
{ error: "Ocorreu um erro no servidor!" },
{ status: 500 }
);
}
}
Page:
import { Button } from "@/components/ui/button";
import Link from "next/link";
import EventList from "@/components/events/event-list";
import axios, { AxiosError } from "axios";
import { Event } from "@prisma/client";
type Props = {};
export default async function EventsPage({}: Props) {
const events = await getUserEvents();
async function getUserEvents() {
try {
const res = await axios.get<Event[]>(
);
return res.data;
} catch (e) {
if (e instanceof AxiosError) {
console.log(e.response?.data);
}
console.log("error");
return [];
}
}
return (
<div className="space-y-5">
<header className="flex justify-between ">
<h1 className="font-bold text-xl">Meus Eventos ({events?.length})</h1>
<Button>
<Link href="/events/new">Criar Evento</Link>
</Button>
</header>
<EventList data={events} />
</div>
);
}
It always returns "access denied" when I fetch from the page on server, but if I use 'http://localhost:3000/api/events' on the browser e get the correct response
export async function GET(req: Request) {
try {
const currentUser = await getCurrentUser();
console.log(currentUser);
if (!currentUser) {
return Response.json({ error: "Acesso não autorizado" }, { status: 401 });
}
const list = await prisma.event.findMany({
where: {
userId: currentUser.id,
},
});
return Response.json(list);
} catch (e: any) {
if (e instanceof ZodError) {
return Response.json(
{ errors: SimplifyErrors(e.errors) },
{ status: 400 }
);
}
console.log("[ERROR] POST - /api/events");
console.log(e);
return Response.json(
{ error: "Ocorreu um erro no servidor!" },
{ status: 500 }
);
}
}
Page:
import { Button } from "@/components/ui/button";
import Link from "next/link";
import EventList from "@/components/events/event-list";
import axios, { AxiosError } from "axios";
import { Event } from "@prisma/client";
type Props = {};
export default async function EventsPage({}: Props) {
const events = await getUserEvents();
async function getUserEvents() {
try {
const res = await axios.get<Event[]>(
${process.env.SERVER_URL}/api/events);
return res.data;
} catch (e) {
if (e instanceof AxiosError) {
console.log(e.response?.data);
}
console.log("error");
return [];
}
}
return (
<div className="space-y-5">
<header className="flex justify-between ">
<h1 className="font-bold text-xl">Meus Eventos ({events?.length})</h1>
<Button>
<Link href="/events/new">Criar Evento</Link>
</Button>
</header>
<EventList data={events} />
</div>
);
}
It always returns "access denied" when I fetch from the page on server, but if I use 'http://localhost:3000/api/events' on the browser e get the correct response
Answered by Clown
Where does getCurrentUser come from?
I suspect its just a issue with not passing the session/headers.
You'll need to pass the headers in the fetch in that case.
I suspect its just a issue with not passing the session/headers.
You'll need to pass the headers in the fetch in that case.
const salesCountRes = await fetch(.... , {
headers: new Headers(headers()),
});4 Replies
Where does getCurrentUser come from?
I suspect its just a issue with not passing the session/headers.
You'll need to pass the headers in the fetch in that case.
I suspect its just a issue with not passing the session/headers.
You'll need to pass the headers in the fetch in that case.
const salesCountRes = await fetch(.... , {
headers: new Headers(headers()),
});Answer
note: that new Header() wrapper is purely because vercel bugs out otherwise. I dont know if its a issue with just vercel or other hosts aswell
@Clown Where does getCurrentUser come from?
I suspect its just a issue with not passing the session/headers.
You'll need to pass the headers in the fetch in that case.
js
const salesCountRes = await fetch(.... , {
headers: new Headers(headers()),
});
Japanese common catfishOP
actions/getCurrentUser.ts
import { prisma } from "@/lib/prismadb";
import getSession from "./getSession";
export default async function getCurrentUser() {
try {
const session = await getSession();
if (!session?.user?.email) {
return null;
}
const user = await prisma.user.findUnique({
where: { email: session.user.email as string },
});
if (!user) {
return null;
}
return user;
} catch (error) {
console.log("Error getting session", error);
return null;
}
}
actions/getSession.ts
import { authOptions } from "@/lib/auth";
import { getServerSession } from "next-auth";
export default async function getSession() {
return await getServerSession(authOptions);
}
import { prisma } from "@/lib/prismadb";
import getSession from "./getSession";
export default async function getCurrentUser() {
try {
const session = await getSession();
if (!session?.user?.email) {
return null;
}
const user = await prisma.user.findUnique({
where: { email: session.user.email as string },
});
if (!user) {
return null;
}
return user;
} catch (error) {
console.log("Error getting session", error);
return null;
}
}
actions/getSession.ts
import { authOptions } from "@/lib/auth";
import { getServerSession } from "next-auth";
export default async function getSession() {
return await getServerSession(authOptions);
}
@Clown Where does getCurrentUser come from?
I suspect its just a issue with not passing the session/headers.
You'll need to pass the headers in the fetch in that case.
js
const salesCountRes = await fetch(.... , {
headers: new Headers(headers()),
});
Japanese common catfishOP
Thank you very much, I added headers and it worked.
const res = await fetch(`${process.env.SERVER_URL}/api/events`, {
headers: new Headers(headers()),
});