#server actions

1 messages · Page 1 of 1 (latest)

stuck kite
#

so are server actions the same as an api route but in the same file?

thin fjordBOT
#

Hi @stuck kite. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Server Actions in Next.js are not exactly the same as API routes, but they do share some similarities. Both are used to handle server-side operations, but they are used in different ways and have different capabilities.

API routes provide a solution to build a public API with Next.js. Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page. They are server-side only bundles and won't increase your client-side bundle size (source (https://nextjs.org/docs/pages/building-your-application/routing/api-routes)).

On the other hand, Server Actions are a new feature in Next.js that allow you to define asynchronous server functions that can be called directly from your components, without needing to manually create an API Route. They enable server-side data mutations, reduced client-side JavaScript, and progressively enhanced forms (source (https://nextjs.org/blog/june-2023-update#new-react-features)).

Server Actions can be defined in two places: inside the component that uses it (Server Components only), or in a separate file (Client and Server Components), for reusability. You can define multiple Server Actions in a single file (source (https://nextjs.org/docs/app/api-reference/functions/server-actions)).

Here's an example of how to define a Server Action inside a Server Component:

export default function ServerComponent() {
 async function myAction() {
 'use server'
 // ...
 }
}

And here's how to define a Server Action in a separate file and import it into a Client Component:

// app/actions.js
'use server'
 
export async function myAction() {
 // ...
}
#

// app/client-component.jsx
'use client'

import { myAction } from './actions'

export default function ClientComponent() {
return (
<form action={myAction}>
<button type="submit">Add to Cart</button>
</form>
)
}


In summary, while Server Actions and API routes both handle server-side operations, they are used in different ways and offer different capabilities. Server Actions provide a more integrated and flexible way to handle server-side operations directly from your components.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

@stuck kite kapa.ai is still learning and improving, please let us know how it did by reacting below

stuck kite
#

@thin fjord so these server actions are private and are not public (api routes are public)
so on a form submission, i redirect the user to a new page. i need to run some backend server code on page load.
should i use api routes or server actions

thin fjordBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Based on the information provided in the extracts, both API Routes and Server Actions can be used to run server-side code. However, the choice between the two depends on your specific use case and requirements.

API Routes are indeed public and are typically used to build APIs that can be accessed externally. They do not specify CORS headers by default, meaning they are same-origin only (source (https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations)).

Server Actions, on the other hand, are designed for deep integration with the rest of the data lifecycle in Next.js, including the Next.js Cache, Incremental Static Regeneration (ISR), and the client router. They allow you to define asynchronous server functions that can be called directly from your components, without needing to manually create an API Route (source (https://nextjs.org/blog/next-13-4#server-actions-alpha)).

If you need to run some backend server code on page load and then redirect the user to a new page, you might want to consider using Server Actions. They have been designed to allow mutating, re-rendering the page, or redirecting to happen in one network roundtrip, ensuring the correct data is displayed on the client, even if the upstream provider is slow (source (https://nextjs.org/blog/next-13-4#server-actions-alpha)).

Here's an example of how you might use a Server Action to update data and then revalidate the page:

import db from './db';
import { revalidateTag } from 'next/cache';
 
async function update(formData: FormData) {
 'use server';
 await db.post.update({
 title: formData.get('title'),
 });
 revalidateTag('posts');
}
 
export default async function Page() {
 const res = await fetch('<https://...',> { next: { tags: ['posts'] } });
 const data = await res.json();
 // ...
}
#

However, please note that as of the time of the extracts, Server Actions are still in alpha and are not recommended for use in production yet (source (https://nextjs.org/blog/june-2023-update#new-react-features)). If you need a stable solution for production, you might want to stick with API Routes for now.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@stuck kite kapa.ai is still learning and improving, please let us know how it did by reacting below

stuck kite
#

@thin fjord if i want to make a pay to use public api in the future, wouldnt it be better to just make an api route?

thin fjordBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, if you're planning to create a pay-to-use public API in the future, using API Routes would be the more appropriate choice. API Routes in Next.js are designed to create endpoints that can be accessed externally, making them suitable for building public APIs.

API Routes provide a solution to build a public API with Next.js. Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page. They are server-side only bundles and won't increase your client-side bundle size (source (https://nextjs.org/docs/pages/building-your-application/routing/api-routes)).

Here's an example of how to create an API Route that returns a JSON response:

// pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'
 
type ResponseData = {
 message: string
}
 
export default function handler(
 req: NextApiRequest,
 res: NextApiResponse<ResponseData>
) {
 res.status(200).json({ message: 'Hello from Next.js!' })
}

Remember, when creating a public API, you'll also need to consider aspects like rate limiting, authentication, and error handling, which are not covered in the provided extracts.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@stuck kite kapa.ai is still learning and improving, please let us know how it did by reacting below

stuck kite
#

@thin fjord so how can i add a api request to my route in this file (it needs to run on page load, and be cached)

thin fjordBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To add an API request to your route that runs on page load and is cached, you can use the fetch function provided by Next.js. This function extends the native Web fetch() API to allow each request on the server to set its own persistent caching semantics.

Here's an example of how you might use fetch in your page:

// app/page.tsx
export default async function Page() {
  // This request should be cached until manually invalidated.
  // Similar to `getStaticProps`.
  // `force-cache` is the default and can be omitted.
  const staticData = await fetch(`<https://...`,> { cache: 'force-cache' })
 
  // This request should be refetched on every request.
  // Similar to `getServerSideProps`.
  const dynamicData = await fetch(`<https://...`,> { cache: 'no-store' })
 
  // This request should be cached with a lifetime of 10 seconds.
  // Similar to `getStaticProps` with the `revalidate` option.
  const revalidatedData = await fetch(`<https://...`,> {
    next: { revalidate: 10 },
  })
 
  return <div>...</div>
}

In this example, staticData will be cached until manually invalidated, dynamicData will be refetched on every request, and revalidatedData will be cached with a lifetime of 10 seconds (source (https://nextjs.org/docs/app/api-reference/functions/fetch)).

Please replace <https://...> with the actual URL of your API endpoint.

Remember, the fetch function is only available in Next.js 12 or later. If you're using an older version of Next.js, you'll need to use a different method to fetch data on the server, such as getStaticProps or getServerSideProps.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: