reactjslaravelfetch-apinext.js13laravel-sanctum

Issue with Using Next.js 13 Server Components and Laravel Sanctum Authentication for User Data Retrieval


I have a Laravel application that uses Sanctum for authentication. I'm currently working on a Single Page Application (SPA) with Next.js 13, utilizing the app router and server components. I have successfully retrieved user details when making requests from a client component using Axios, following the example from the Breeze repository.

However, I'm struggling to retrieve authenticated user details from a server component in Next.js 13 using the fetch function. I've attempted to include cookies and set {credentials: 'include'} in the request headers, as shown in the code snippet below:

// api/user/route.ts
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'

const getHeadersWithAuth = () => {
    const headers = new Headers();
    headers.append('Cookie', formatCookies())
    return headers;
};

const formatCookies = () => {
    const cookieStore = cookies()
    const result =  cookieStore.getAll().map((cookie) => (
        !cookie.name.startsWith("_") ? `${cookie.name}=${cookie.value}` : null
    )).filter((cookie) => (cookie));
    return result.join("; ");
};

export async function GET(request: Request) {
    const res = await fetch(process.env.NEXT_PUBLIC_BACKEND_URL + '/api/user', {credentials: 'include', headers: getHeadersWithAuth()});
    return NextResponse.json({'user':  await res. text() })
}

Despite my efforts, I haven't been able to make this work. I'm unsure of what I might be missing or whether this is even possible. Any help or guidance would be greatly appreciated


Solution

  • Looked everywhere and couldn't find the answer, but finally experiments brought me to this result. Basically you set laravel_session by yourself. I'm not sure if this is the right way, but it certainly works with server components.

    async function getData() {
    try {
        const res = await fetch("http://localhost:8000/api/user", {
            headers: {
                Cookie: `laravel_session=${
                    cookies().get("laravel_session")?.value
                }`,
            },
            credentials: "include",
        });
    
        return res.json();
    } catch (error) {
        console.error("Error:", error);
    }
    }