Tips for creating a dynamic route with NextJs 14 API

Looking to start a blog with Next.js 14 and I'm working on defining a function in api/posts/[postSlug]/route.js. How do I access the postSlug parameter within this function?

Here's my current function code:

// api/posts/[postSlug]/route.js
import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";


export async function GET (request) {

    // const { postSlug } = params;
    const postSlug = 'test'
    console.log(request);

    const post = await prisma.post.findUnique({
        where: {
            slug: postSlug
        }
    })

    if (post)
        return NextResponse.json({
            post,
        })

    return NextResponse.json({
        status: 'error',
        message: 'not found!'
    })
}

Answer №1

If you want to retrieve the dynamic route parameters of a route handler, simply access the params object within the second function argument. Here's an example:

// app/products/[id]/route.ts

export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  const { id } = params;
  // ...
}

To learn more about route handlers and their capabilities, check out the official documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Maintaining the position of the screen as you type in information that is located outside of the container

I am encountering an issue with the input/text-area element in absolute position extending halfway outside the container. The screen position seems to follow the caret as I type, but I'd prefer to keep writing and have part of the text hidden beyond t ...

How should I proceed if a TypeScript definition file that I am relying on is lacking a specific definition?

I have encountered an issue while using the React type definitions for my project. The focus method is missing on elements in the array returned by the refs property, which prevents me from getting a specific example to work. The compiler error states: pro ...

Leveraging Nodemailer on Heroku

I have deployed a Next.js app with Heroku at . The app includes a contact form with a submit button that successfully sends an email when I run it locally using npm install, npm run build, npm start. However, when I try to use the app on the Heroku URL, it ...

"Converting array into a string in TypeScript/Javascript, but unable to perform operations

After generating a string with the correct structure that includes an array, I am able to navigate through the JSON on sites like However, when attempting to access the array, it turns out that the array itself is null. Here is the scenario: Firstly, th ...

Struggling to capture an error generated by Sequelize within a universal Middleware block

In a test project, I have successfully implemented CLS transaction control in Sequelize using 'cls-hooked'. The transactions work seamlessly both in the command line and with Express. They are injected and managed automatically, rolling back on a ...

Having trouble getting Framer Motion animation to function in Next.js version 13.4.19?

Struggling to implement animations in my Next.js application with Framer Motion due to a unique file structure. The animations are not behaving as expected. Here is the unconventional file structure I am working with: File Structure Currently using NextJS ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

What is the best way to prioritize items on a list in JavaScript?

Looking to organize your to-do list items by priority? In this task list, users can enter an item, select a priority level, and add it to the list. Here is an example HTML form: <input id="task" type="text"/> <select id="priority"> <o ...

Having trouble with implementing ng-hide and ng-show functionality

I have been working on creating my very first Angular website and so far, everything has been going smoothly with the first page. However, I am facing an issue with the second page not appearing as expected when it meets the condition set with ng-show in t ...

Strategies for redirecting a PDF download response from an API (using node/express) to a user interface (built with React)

I have a specific setup where the backend server generates a PDF, and when a certain endpoint is visited, it triggers the download of the PDF. However, due to security restrictions, I cannot access this endpoint directly from the frontend. To overcome this ...

the process of altering properties in vue js

After running my Vue file, I encountered the following console error. As someone new to Vue programming, I'm attempting to utilize a Syncfusion UI component to display a grid. Prop being mutated: "hierarchyPrintMode" I am unsure where to add the comp ...

Creating an input field within a basic jQuery dialog box is not possible

Can anyone assist me in adding an input box to my dialog box? I am working with jquery-ui.js. Here is the code I currently have: $(document).on("click",".savebtn",function(). { var id = $(this).attr("id"); $.dialog({ ...

Utilizing Discord.js to enable a command for a particular channel

Running a Discord.js bot and struggling to figure out how to restrict the command! help to only the #commands channel. Already have the channel ID, so what steps should be taken in the command event to achieve this? Appreciate any guidance! ...

Can you explain how to incorporate a node module script into a React.js project?

I have encountered an issue where the element works perfectly fine when using an external node module, but fails to function properly when using a locally downloaded node module. Unfortunately, I am unable to identify the root cause of this problem. You c ...

Javascript - Execute function after all nested forEach loops have finished running

I'm finding this task to be quite challenging, as I am struggling to comprehend it fully at the moment. The issue involves nested forEach loops, and I require a callback function to execute once all the loops have finished running. I am considering u ...

Receiving a k6 response that includes a JSON object with a lengthy integer value

During a performance test, I encountered an issue where the response contained items like: {"item":{"id":2733382000000000049}} When parsed using k6's response.json(), it appeared as : {"item":{"id":273338200000 ...

Create personalized styles for each item within a stack with specific spacing using the @mui library

Is there a way to change both the background color and spacing area when hovering over each item in my list? https://i.stack.imgur.com/87TST.png <Stack spacing={4} divider={<Divider variant={`fullWidth`} orientation={`horizontal`} flexItem/>}> ...

Integrate Vue Login Functionality using Axios HTTP Requests

Hello everyone! I am new to Vue and currently struggling with making an HTTP Request to my backend. When I check the browser console, I can see the access token retrieved from /login endpoint but when I try to fetch data from api/users, it returns "Token ...

ajax duplicator and reset form tool

Hello everyone, I have a website where users can add their experiences. While adding an experience, they can dynamically add and remove more fields. One of the input fields is for a date, but when the data is submitted, the same date appears for all entrie ...

The components for my children are not being displayed within the Drawer component in Material UI and React

Why are the Material UI components and other project components not displayed when I use my DrawerForm component? List of dependencies: react: 18.2.0 react-dom: 18.2.0 @amcharts/amcharts5: 5.3.6 @mui/icons-material: 5.11.11 @mui/material: 5.11.12 Code s ...