Data Fetching from Server Side in NEXT JS 14 Using App Router

Free


Data Fetching from Server Side in NEXT JS 14 Using App Router


Next JS

Snapshots


Step 1: Follow the following link to setup API Routes with MySQL DB in Next JS 14
https://codingmstr.com/project/creating-api-routes-in-next-js-14-get-post-put-delete


Step 2: Create a 'users/page.jsx' file under 'src/app' directory 


Step 3: Use the below code to fetch server side data in Next JS




export default async function Page() {

    async function create() {
        'use server'
        const response = await fetch('http://localhost:3000/api/users');
        if (response.ok) {
            const json = await response.json();
            console.log(json);
            return json;
        } else {
            console.error('Failed to fetch data:', response.statusText);
            return null;
        }
    }

    const data = await create();

    return (
        <>
            <h2>Users Details</h2>
            Name: {data[0].name}
            {data.map((item, index) => (
                <div key={index}>
                    {item.name}
                </div>
            ))}
        </>
    )

}



Related Projects


Recent Comments

Latest Comments section by users