#route.ts layout
1 messages · Page 1 of 1 (latest)
In Next.js, you can create a custom request handler for a given route using the Web Request and Response APIs. This is done in the app directory using Route Handlers. Here's a basic example of how you might structure your route.ts file:
export async function GET(request: Request) {
// Your logic here
}
This function will be triggered when a GET request is made to the corresponding route. You can access the query parameters (like word in your example) from the request object.
However, the knowledge sources provided do not include a specific example of handling query parameters or fetching data from an external API. For more detailed information on how to handle these cases, you can refer to the Next.js documentation on data fetching (https://nextjs.org/docs/app/building-your-application/data-fetching) and Route Handlers (https://nextjs.org/docs/app/building-your-application/routing/route-handlers).
Please note that if you previously used API routes to call an external API from the client, you can now use Server Components instead to securely fetch data.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@molten sonnet kapa.ai is still learning and improving, please let us know how it did by reacting below
Let me check the knowledge base for you. One moment! :books:
In Next.js, you can extract query parameters from the request object using the request.url property, which gives you the URL of the request. You can then use the URL and URLSearchParams APIs to parse the URL and extract the query parameters.
Here's an example of how you might do this:
export async function GET(request: Request) {
const url = new URL(request.url);
const params = new URLSearchParams(url.search);
const word = params.get('word');
// Your logic here
}
In this code, request.url gives you the URL of the request. new URL(request.url) creates a new URL object from the request URL, and url.search gives you the query string part of the URL. new URLSearchParams(url.search) creates a new URLSearchParams object from the query string, which you can then use to get the value of the word parameter with params.get('word').