[GH-ISSUE #823] Nextjs API getSession() is not working. #8453

Closed
opened 2026-04-13 03:31:19 -05:00 by GiteaMirror · 3 comments
Owner

Originally created by @togisoft on GitHub (Dec 8, 2024).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/823

I do getSession with Nextjs App router API, but when I do fetch, I get a 401. Why?.I couldn't find a solution to this.

/**
 * GET API Route: Get all colors.
 */
async function getColors(req: NextRequest): Promise<NextResponse> {
    await connectToDatabase();

    try {
        const session = await auth.api.getSession({
            headers: await headers(),
        })


        if (!session) {
            return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
        }

        if (session.user.role !== "admin") {
            return NextResponse.json({ message: "Forbidden: Admins only" }, { status: 403 });
        }

        const colors = await ColorModel.find()
            .populate("name")
            .lean();

        return NextResponse.json(colors, { status: 200 });
    } catch (error: any) {
        console.error("Error fetch colors", error.message);
        return NextResponse.json(
            { error: { message: error.message || "An unkown error occurred!" } },
            { status: 400 }
        )
    }
}

export const GET = getColors;
import { $fetch, $fetchBetter } from "@/lib/fetch";
import { Color } from "@/types/catalog/attributes";
import { LocalesData } from "@/types/locales-data";
import Client from "./client";

export default async function Page() {
    const [locales, colors] = await Promise.all([
        $fetchBetter<LocalesData>("/locales"), // Locales API'si
        $fetch<Color[] | null>("/catalog/attributes/colors"), // Categories API'si
    ]);

    return (
        <Client params={{
            localesData: locales.data!
        }} />
    );
}
Originally created by @togisoft on GitHub (Dec 8, 2024). Original GitHub issue: https://github.com/better-auth/better-auth/issues/823 I do getSession with Nextjs App router API, but when I do fetch, I get a 401. Why?.I couldn't find a solution to this. ```ts /** * GET API Route: Get all colors. */ async function getColors(req: NextRequest): Promise<NextResponse> { await connectToDatabase(); try { const session = await auth.api.getSession({ headers: await headers(), }) if (!session) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); } if (session.user.role !== "admin") { return NextResponse.json({ message: "Forbidden: Admins only" }, { status: 403 }); } const colors = await ColorModel.find() .populate("name") .lean(); return NextResponse.json(colors, { status: 200 }); } catch (error: any) { console.error("Error fetch colors", error.message); return NextResponse.json( { error: { message: error.message || "An unkown error occurred!" } }, { status: 400 } ) } } export const GET = getColors; ``` ```ts import { $fetch, $fetchBetter } from "@/lib/fetch"; import { Color } from "@/types/catalog/attributes"; import { LocalesData } from "@/types/locales-data"; import Client from "./client"; export default async function Page() { const [locales, colors] = await Promise.all([ $fetchBetter<LocalesData>("/locales"), // Locales API'si $fetch<Color[] | null>("/catalog/attributes/colors"), // Categories API'si ]); return ( <Client params={{ localesData: locales.data! }} /> ); } ```
GiteaMirror added the locked label 2026-04-13 03:31:19 -05:00
Author
Owner

@Bekacru commented on GitHub (Dec 8, 2024):

try to see if headers have better_auth cookies. Also you can directly pass the headers from the request. req.headers

<!-- gh-comment-id:2526272565 --> @Bekacru commented on GitHub (Dec 8, 2024): try to see if `headers` have `better_auth` cookies. Also you can directly pass the headers from the request. `req.headers`
Author
Owner

@togisoft commented on GitHub (Dec 8, 2024):

When I added the headers like this it worked.

import { $fetch } from "@/lib/fetch";
import { LocalesData } from "@/types/locales-data";
import Client from "./client";
import { Color } from "@/types/catalog/attributes";
import { headers } from "next/headers";

export default async function Page() {
    const [locales, colors] = await Promise.all([
        $fetch<LocalesData>("/locales"), // Locales API'si
        $fetch<Color[] | null>("/catalog/attributes/colors", {
            headers: await headers() as any
        })
    ]);
    return (
        <Client params={{
            localesData: locales.data!,
            colors: colors.data
        }} />
    );
}
<!-- gh-comment-id:2526325301 --> @togisoft commented on GitHub (Dec 8, 2024): When I added the headers like this it worked. ```ts import { $fetch } from "@/lib/fetch"; import { LocalesData } from "@/types/locales-data"; import Client from "./client"; import { Color } from "@/types/catalog/attributes"; import { headers } from "next/headers"; export default async function Page() { const [locales, colors] = await Promise.all([ $fetch<LocalesData>("/locales"), // Locales API'si $fetch<Color[] | null>("/catalog/attributes/colors", { headers: await headers() as any }) ]); return ( <Client params={{ localesData: locales.data!, colors: colors.data }} /> ); } ```
Author
Owner

@Bekacru commented on GitHub (Dec 14, 2024):

that's the intended behavior closing this as resovled

<!-- gh-comment-id:2542830066 --> @Bekacru commented on GitHub (Dec 14, 2024): that's the intended behavior closing this as resovled
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#8453