πŸ”Œ Basics of calling an API

The apiRequest function is used to send data to the server or retrieve something from the database. It's your go-to method when performing actions like saving users, fetching records, or processing logic server-side.


πŸ“ Example Structure

src/
    dashboard/
        page.tsx
        _components/
        _functions/
        _api/
            saveUser.ts
            deleteUser.ts
    home/
        page.tsx

βœ… The folder name must end in api, such as _api or _dashboardApi.

🚫 Api routes are scoped to their route folder. In the example above, saveUser can be called only from /dashboard. It won't be available on /home or other pages.

πŸ’‘We recommend starting folder names with an underscore (_) to indicate that it’s a non-route folder, making the project structure easier to read for other developers.

This structure allows you to use the same API name in different places (e.g. saveUser on /dashboard and /home), without any conflict.


πŸ›‘ Where You Can and Can't Call

  • βœ… Can call apiRequest({ name: "refreshData", data: { name: 'Mike' } }) from inside the page.tsx or components under the same route (e.g. /dashboard)

  • ❌ Cannot call a api route that belongs to a different page route (e.g., trying to call /home/_api/refreshData from /dashboard)


βš™οΈ How to use apiRequest

Since apiRequest returns a Promise, you need to call it inside an async function.

❗ You cannot call it directly in the top-level body of a React component.

βœ… Use it like this inside a useEffect handler:

You can find more advanced usage and patterns on the next page.

Last updated