Reputation: 6814
The next.js documentation is very clear about data fetching and how to create dynamic API routes. I wonder what is the correct way to trigger an action/method on the server-side. I.e. if I want to subscribe to a newsletter, there would be a button "Subscribe". When the user clicks the button, the users email address should be inserted into the database as a subscriber.
Based on the documentation I would create POST API endpoint by adding this to pages/api/subscribe.js
:
function signup(emailAddress) {
// do arbitrary database connection work here and insert into subscriber table
}
export default function handler(req, res) {
if (req.method === "POST") {
signup(req.body.emailAddress)
res.json({ status: 'ok' })
}
}
Now, in the onClick()
of the "Susbcribe" button, I could use fetch()
to send that post request to /api/subscribe
along with a JSON payload, but the documentation of nextjs explicitly states not to do that. Also, there is only getServerSideProps()
that I could use in the next.js page code - but we do not want to signup a user upon page load, it is a single action/method after which the user should be redirected to a success page.
Additionally, it is obvious that in a client-side component I cannot import signup()
since it contains server-side nodejs code.
Basically this question boils down to: "Okay, I can fetch data with getServerSideProps()
without creating a REST API, but how do I perform server-side actions/invocations without creating and calling a REST API upon user interaction?".
Upvotes: 2
Views: 1830
Reputation: 1610
The docs have info on this nowdays. There are the server-actions that should provide what is aimed for here. One of the models is to use the state from html with the form element and pass input data via it to a server side function. example:
const handleSubmit = async () => {
'use server'; do fetch...} use in JSX: <form action={handleSubmit}>
So this way you are not bound to client components for event handlers and can stay on server side and do not need to create any API Routes. Then you might need to revalidate the cache somewhere, in the function or maybe on navigation to get the mutation to appear. Here: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations. I don't tho know if I am a huge fan of this kind of "obfuscation" against more traditional ways in general:)
Upvotes: 0
Reputation: 6814
After having used Next.js for 1+ years and worked with both App+Pages router, I just have to say there is no such thing in NextJS. Performing server-side mutations is not covered by NextJS.
If you need a React framework that also handles mutations, take a look at Remix.
Upvotes: 0