Getting POST data in Next.js is a common task that requires understanding of how the

I am currently working on a form validation project using the App Router within Next.js.

// app/register/page.tsx
export default function Register(context: any) {
    console.log("Register page", context.params, context.searchParams);
    return (
        <form method={'POST'} action={'/register'} >
            <input name="usr"/>
            <input name="pwd"/>
            <button type={'submit'}>Submit</button>
        </form>
    );
}

I'm trying to figure out how to retrieve the data sent by the user through POST, but it appears that I can only access parameters from the URL using context.searchParams and context.params.

Any suggestions on what steps I should take next?

Thanks for your help!

Answer №1

Try implementing Router Handlers

For instance:

// app/test/route.ts

import {NextResponse} from 'next/server'

export async function POST(request: Request) {
    const res = await request.json()
    console.log(request);
    console.log(res);
    return NextResponse.json({hello: 'world'})
}

You can test it in a web browser by accessing http://url/test

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

Error in Typescript: Cannot assign type 'string[]' to type 'string'

I'm currently developing a project using Next.js with Typescript and .tsx files, and I'm utilizing Supabase as my database. While everything is functioning perfectly on localhost, I'm encountering an issue when trying to build the project o ...

The process of AJAX polling a JSON-returning URL using jQuery's $.ajax() method does not appear to provide up-to-date responses

I am currently working on a project that involves polling a specific URL for a JSON response using AJAX. The initial AJAX request alerts the server of my need for JSON content, prompting it to start building and caching the response. Subsequent AJAX reques ...

"Create a React-Bootstrap Navbar featuring a distinctive design with 2 rows

Can someone help me create 2 rows of Navbars using React-Bootstrap? I came across a similar question on Stackoverflow at this link, but my attempts so far have been unsuccessful. Below is the code I'm currently working with. ........ const Header = ( ...

Activate radio button exclusively for admin user

My current application includes an admin panel with functions to manage users. I use a while loop in the form creation to display 3 user types: Admin, Manager, and User, which are pulled from a database. Admin Manager User This is how my HTML Form look ...

Improving React efficiency: What techniques can be used to prevent the entire component from re-rendering every time a prop changes?

Issue at Hand I created a custom component named PageLayoutSideBar.tsx that accepts two props: sideBar and content. This component is designed to make it easy to display the sideBar and page content with the appropriate styling and sidebar width. My conce ...

Is there a way to prevent a premature closure of a connection?

I'm currently faced with the task of moving a substantial amount of data from a MySQL database, exceeding the maximum query size. To accomplish this, I need to process it in chunks through a loop. However, encountering an issue where about half of the ...

Is it within the realm of possibility for a route-handling function to accept more than two parameters?

Recently, I started learning about node js and delved into the world of jwt authentication. While going through some code snippets, I came across a request handler in express that caught my attention. app.post('/login',function(req,res){...}); ...

React suspense triggers a fallback reload

Is there a way to prevent the Suspense fallback from being shown after the first render or when the image is cached? I have an image fetched from an API endpoint and am importing it within a Suspense component with a fallback. However, every time useState ...

Unable to find the specified element within Gmail

Recently, I've been working on a project with Nightwatch.js where it checks the dev environment and sends a test email to a Gmail account. Following that, it logs into Gmail, locates and clicks on the correct email. My main challenge now is trying to ...

What is the best way to add a base path to every route managed by Next.js?

Currently, I am in the process of revamping an existing expressjs application that utilizes jade for the user interface to a nextjs application. The same app serves as the API server for external applications. All web app routes are currently located under ...

Reorder elements in CSS Grid

I've been working with a css-grid and it's almost there, but I'm stuck on reordering the items in a specific way. Currently, the html layout is set as “1, 2, 3, 4,…10”, but for smaller screens, I want the visual order to be “1, 2, 4 ...

Efficiently convert a JSON array into an HTML table using the Jquery

Currently, I'm facing a challenge in my project. The issue arises when a query is sent to the server using jQuery, and an array is returned as a response. My struggle lies in transferring this data to a dynamic table since the column count varies with ...

Activate the bootstrap modal display using PHP code

Can someone help me trigger the modal('show') event using PHP code? I attempted the following: if(isset($_POST['Edit'])){ echo "<script> $('#Modal').modal('show') </script>"; } I tested this code, but i ...

Exploring the integration of Firebase with the latest NextJS 13 Server Components

Hey everyone, I've noticed there isn't a lot of information out there about integrating Firebase with NextJS 13+ to fetch data from firestore and render it on the server using server components. Is this functionality possible with Firebase, or d ...

Is it possible to validate only the fields that are currently visible using HTML form validation

I need a solution for excluding hidden fields from HTML form validation. My situation involves having two groups of form fields, each with some required attributes. Depending on user selection, one group may be hidden, and those fields should not contribut ...

Vue 3 project experiencing issue with Bootstrap 5 tabs failing to update upon tab click

Currently, I'm in the process of developing a vue3 application with bootstrap 5. As part of this project, I am implementing tabs. Although I can successfully click on the tabs, I have encountered an issue where the tab-content remains fixed on the ini ...

Running concurrently, the JavaScript if and else statements execute together

I am looking to create a clickable link that changes the background color when clicked. If the same link is clicked again, I want the background to return to its original state. Here is my current script: <div style="background: transparent;" onclick=" ...

Attempting to access an avatar image via an API, only to encounter an error message indicating that the avatar is not defined

userData is a function that retrieves user data from an API using getUserByChainAccount. The username required by getUserByChainAccount is dynamically fetched from buyer. I'm trying to access the avatar, but I keep encountering the error message Unha ...

CSS styling doesn't take effect until the page is reloaded due to the failure of cssText

After generating a new list item, it appears that the CSS styling is not being inherited until the page is reloaded. Even though I have added styling using cssText dynamically, it doesn't seem to be working as expected. I've attempted using cssT ...

Organizing a list based on the text within span elements using either jQuery or underscore

I'm a bit confused about how to arrange an unordered list by the content of the span within each list item. Here is my HTML code: <ul id="appsList"> <li><span>aa</span> <span class="sort">androi ...