Parameterized Server Actions
Create a Next.js 14 server action that accepts URL parameters to fetch and return specific resources from a database.
import { NextRequest, NextResponse } from 'next/server';
// This function represents the Server Action
export async function action(req) {
// Extracting the URL parameter 'resourceId'
const { resourceId } = req.nextUrl.query;
// Fetch the specific resource from the database
// You should replace 'databaseApiCall' with your actual database fetch function
const resource = await databaseApiCall(resourceId);
// Return the resource in the response
return new NextResponse(JSON.stringify(resource), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
}
// Example database fetch function (should be replaced with your database logic)
async function databaseApiCall(id) {
// Replace with actual database fetching logic
// Here we simulate fetching the resource by returning an object
return { id, name: 'Resource Name', description: 'Resource Description' };
}
This piece of code defines a Next.js Server Action that fetches a resource from a database using a URL parameter. It uses a mock 'databaseApiCall' function to simulate fetching data which should be replaced with actual database interaction logic.