how to fetch data from api in next js 14

Опубликовано: 24 Июль 2026
на канале: CodeHelp
12
0

Download 1M+ code from https://codegive.com/a43bb88
fetching data from an api in next.js 14 can be done using various methods depending on whether you want to fetch data on the server-side, client-side, or during the build time. below, i'll walk you through how to do this using the recommended approaches in next.js 14.

prerequisites

make sure you have the following before you start:

1. **node.js**: ensure that you have node.js installed (preferably v14 or higher).
2. **next.js**: you can create a new next.js app using the command:

```bash
npx create-next-app@latest my-next-app
cd my-next-app
```

3. **api**: you’ll need an api to fetch data from. for demonstration, we can use a public api like jsonplaceholder or any other restful api.

fetching data in next.js

1. using server-side rendering (ssr)

ssr allows you to fetch data on each request. this is useful for pages that need to display dynamic content.

**example**: fetching data from jsonplaceholder

```javascript
// pages/posts.js

import react from 'react';

const posts = ({ posts }) = {
return (
div
h1posts/h1
ul
{posts.map(post = (
li key={post.id}
h2{post.title}/h2
p{post.body}/p
/li
))}
/ul
/div
);
};

export async function getserversideprops() {
const res = await fetch('https://jsonplaceholder.typicode.com/...
const posts = await res.json();

return {
props: {
posts,
},
};
}

export default posts;
```

in this example:
the `getserversideprops` function fetches data from the api and passes it as props to the `posts` component.
the data will be fetched on every request.

2. using static site generation (ssg)

ssg allows you to fetch data at build time. this is useful for pages that do not change frequently.

**example**: fetching data during build time

```javascript
// pages/posts-static.js

import react from 'react';

const postsstatic = ({ posts }) = {
return (
div
h1static ...

#NextJS #APIIntegration #numpy
Next.js 14
API data fetching
Fetch API Next.js
Next.js API integration
useEffect Next.js
Axios Next.js
SWR Next.js
Next.js data fetching methods
server-side rendering Next.js
client-side data fetching
React hooks API
asynchronous data fetching
Next.js API routes
fetch data example
Next.js data fetching tutorial