How can I retrieve query parameters in the Server app directory of Next.js 13 using a function?

I am looking to retrieve a query token from localhost/get/point?token=hello.

import { NextResponse } from 'next/server'
import base64url from 'base64url'

type Params = {
  token: string
}

export async function GET(req: Request, context: { params: Params }) {
  
  const token = req.query.token


  const tokenData = JSON.parse(base64url.decode(token.split('.')[1]))
  const verifyResult = Jwt.verify(token)
  if (verifyResult == JwtStatusCode.TokenExpired) {
    return NextResponse.json({ error: 'Token expired', message: 'Token expired'}, { status: 401 })
  } else if (verifyResult === JwtStatusCode.TokenInvalid) {
    return NextResponse.json({ error: 'Token invalid', message: 'Token invalid' }, { status: 401 })
  }
  const data = await client.user.findMany({
    where: { name: tokenData.name }
  })
  if (data.length != 0) {
    NextResponse.json({
      point: data[0].point,
      message: 'Success'
    }, { status: 200 })
  }
}

Within the pages directory, I utilized req.query for accessing data, but how does it work in the Next13 app directory?

I experimented with splitting the URL, however, I don't find it to be the most efficient method.

Answer №1

One way to resolve this issue is by utilizing the URL object and searchParams. The function searchParms.get can extract query parameters in the latest version of Next.js.

const { searchParams } = new URL(req.url)
const token = searchParams.get('token') as string

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: Component with nested FormGroup does not have a valid value accessor for form control in Angular

In my setup, the parent component is utilizing a FormGroup and I am expecting the child components to notify any changes in value back to the parent. To achieve this, I am trying to implement NG_VALUE_ACCESSOR in the child component so that it can act like ...

Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example: 4 Categories with Subjects ['A','B','D'] [&a ...

Tips for integrating Reactjs with Chessboard.js

Recently, I stumbled upon chessboardjs (https://chessboardjs.com/) as a way to hone my React coding skills. However, I hit a roadblock while trying to implement a simple example of displaying the chess board in my application. The documentation instructed ...

Implementing TypeScript module resolution with Cucumber-js can be a bit tricky

Currently, I am in the process of creating a Proof of Concept for Cucumber-js using TypeScript. Everything is going smoothly except for one issue - I am facing difficulties when it comes to configuring the module resolution while utilizing tsconfig-paths. ...

Nextjs google places autocomplete not providing accurate suggestions

I'm attempting to utilize Google autocomplete to retrieve the names of mosques specifically in the United Kingdom. However, the data I am receiving is global and not limited to mosques. Here is my code: import axios from "axios"; export def ...

Testing API route handlers function in Next.js with Jest

Here is a health check function that I am working with: export default function handler(req, res) { res.status(200).json({ message: "Hello from Next.js!" }); } Alongside this function, there is a test in place: import handler from "./heal ...

Switch up your component button in Angular across various pages

I've created a new feature within a component that includes a toolbar with multiple buttons. Is there a way to customize these buttons for different pages where the component is used? Component name <app-toolbar></app-toolbar> Component ...

Integrate TypeScript into the current project

As a newcomer to Typescript, I am currently exploring the option of integrating it into my current project. In our MVC project, we have a single file that houses the definitions of all model objects. This file is downloaded to the client when the user fir ...

Tips for fixing the Next.js installation error with yarn: Ensure that options.env['npm_config__p_a_c_k_a_g_e___l_o_c_k_'] is a string that does not contain null bytes

When attempting to create a Next.js app with yarn using "yarn create next-app", an error is thrown stating: An unexpected error occurred: "The property 'options.env['npm_config__p_a_c_k_a_g_e___l_o_c_k_']' must be a string without null ...

Is it possible for the getStaticPaths function to accept dynamic slugs?

Within a file named pages/posts/[...slugs].tsx, the getStaticPaths function is defined as follows: export async function getStaticPaths() { return { paths: [ { params: { slugs: ['1', 'hunt-for-the-hidden-reindeer'] } }, ...

What is the process of bringing async Server Components into Client Components in Nextjs 13?

I've been diving into the world of Next.js 13 app directory and React 18's Server Components. In line with the documentation, I decided to include an async fetch() call within a Server Component while also marking the component as async. However ...

Inject a cookie into the Axios interceptor for the request handler

I am in the process of setting up Axios to always include a request header Authorization with a value from the user's cookie. Here is my code: import axios, { AxiosRequestConfig, AxiosResponse} from 'axios'; import {useCookies} from "react-c ...

How to exclude specific {} from TypeScript union without affecting other types

Consider the following union type: type T = {} | ({ some: number } & { any: string }) If you want to narrow this type to the latter, simply excluding the empty object won't work: type WithEntries = Exclude<T, {}> This will result in neve ...

The Angular Material Table is reporting an error: the data source provided does not conform to an array, Observable, or DataSource

Having some trouble with an Angular Material table, as I'm encountering an error preventing me from populating the grid: Error: Provided data source did not match an array, Observable, or DataSource search.service.ts GridSubmittedFilesList: IGridMo ...

What is the process for integrating custom fields into a product using Stripe, and how can a stock limit be implemented for each customized field?

Currently, as I develop an ecommerce website using Next.js and integrate Stripe for checkout, I've come across the feature of custom fields in Stripe. This feature allows me to add options such as small, medium, and large for clothing sizes. However, ...

This function has a Cyclomatic Complexity of 11, exceeding the authorized limit of 10

if ((['ALL', ''].includes(this.accountnumber.value) ? true : ele.accountnumber === this.accountnumber.value) && (['ALL', ''].includes(this.description.value) ? true : ele.description === this.description.valu ...

Having trouble with loading JavaScript during ng build --prod process

The JavaScript file I'm using for multiple emails (multiple_emails.js plugin) works well with ng serve. Here is my code: (function( $ ){ $.fn.multiple_emails = function(options) { // Default options var defaults = { ...

Tips for including and excluding personalized Chips from input

Just started learning React/typescript, any assistance would be greatly appreciated Custom Chip (CC.chip) is a specialized Chip UI component that can be utilized as demonstrated below. const [isOpen, setIsOpen] = useState(true); const onClose = Re ...

The TypeError encountered in an Ionic pipe states that the property 'toString' cannot be read as it is undefined

I have a news application built in Ionic 4. The pubDate property of the UutinenPage class is being asynchronously assigned a value of data.items[this.id].pubDate in the uutinen.page.ts file. The expected format of this value is something like 2019-02-19 04 ...

The parameters provided for ionic2 do not align with any acceptable signature for the call target

Currently, I have 3 pages named adopt, adopt-design, and adopt-invite. To navigate between these pages, I am using navCtrl.push() to move forward and to go back to the previous page. Everything works smoothly on the browser, but when I try to build it for ...