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

There is no way to convert a strongly typed object into an observable object using MobX

I have been utilizing the MobX library in conjunction with ReactJS, and it has integrated quite smoothly. Currently, I am working with an observable array structured as follows: @observable items = []; When I add an object in the following manner, everyt ...

Create a PDF document utilizing Angular Ignite UI for Angular

Currently working with Angular TypeScript 12, I have successfully integrated Angular Ignite UI grid. However, I am in need of a way to export my grid into a PDF format using Igx-Grid. Does Igx-Grid support PDF exporting? If not, are there any alternative ...

Using Typescript to deliver the parent component's props to its children prop

I have a goal to create a versatile component that can accept different props based on its usage in the project. The component should output its children prop along with all the given props (flow-through) and potentially some new constants calculated based ...

Executing an Observable function in Angular Typescript a single time

Within my Angular application, there exists a service responsible for retrieving data from a server. load.service.ts: load = new Observable(observer => { console.log('load function called'); // asynchronous tasks with time delay obser ...

The shared module for next/router is not found in the shared scope default within Next.js and @module-federation/nextjs-mf

I am working on a JavaScript Turbo repo with a host app that has the following configuration in its next.config.js: const { NextFederationPlugin } = require("@module-federation/nextjs-mf"); const nextConfig = { reactStrictMode: true, ...

Discover every possible path combination

Looking to flatten an array of 1D arrays and simple elements, reporting all combinations until reaching a leaf "node." For example: // Given input array with single elements or 1D arrays: let input = [1, 2, [3, 4], [5, 6]]; The unfolding process splits pa ...

Tips for utilizing the value of object1.property as a property for object2

Within the template of my angular component, I am attempting to accomplish the following: <div> {{object1.some_property.(get value from object2.property and use it here, as it is a property of object1)}} </div> Is there a way to achieve this ...

gulp-webpack is unable to locate node packages

Currently working on developing a modern Angular application. I have opted to use gulp-webpack for quick development builds. To handle my TypeScript bundling and node modules dependencies, I am relying on webpack. However, it seems that gulp-webpack is no ...

How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Compone ...

Creating a Sitemap in Strapi version 3.6.8 using the strapi-plugin.sitemap version 1.2.5

Currently, I am utilizing Strapi v3.6.8 and successfully integrated strapi-plugin-sitemap 1.2.5. Upon entering the data into the plugin, I made the following configurations: Hostname: localhost:1337 Include home page: ON Exclude drafts: ON In addition, ...

Dealing with an unspecified parameter can be tricky - here's how you

Currently, I am in the process of developing an angular application. In this project, there is a specific scenario that needs to be handled where a parameter is undefined. Here's a snippet of my code: myImage() { console.log('test') ...

What causes the discrepancy in button appearance between Next.js 14, next/font, and Tailwind CSS?

I am currently facing a challenge in upgrading to nextjs 14 due to my struggle with incorporating next/font. I have two buttons with identical tailwind classes, except for the last className that pertains to nextjs font. Below is the code snippet: import ...

The issue with functions not executing when triggered by HammerJS

In my application, there is a component that displays information for different days as they are cycled through using the functions dayUp() and dayDown(). Here is an example of how these functions are structured: dayUp() { if (this.dayCount == 7) { ...

The issue with calling a public method from an onchange event triggered by a custom Google Maps control in the Ionic framework has been encountered

Hello, fellow developers! I am relatively new to Ionic and web programming in general. Currently, I am working on a small app that involves integrating the Google Maps JS API. While I have successfully created and loaded the map, as well as added a custom ...

Encountered an error with Aurelia webpack 4 when trying to load a necessary CSS file during runtime

I encountered a unique issue with webpack and aurelia that I can't seem to figure out. After creating a new webpack configuration based on online resources and official documentation, the compilation goes smoothly without any errors. However, during r ...

Encountered an issue while deploying a Next.js app on AWS Amplify: Unable to activate platform for 'staging' due to Access Denied error

\# Launch phase: construct 2023-05-03T02:31:47.363Z \[INFO\]: \[33mTip: Run this command from the main directory of your application\[39m 2023-05-03T02:31:47.908Z \[WARNING\]: - Setting up environment: staging 2023-05-03T ...

Nestjs RabbitMq Microservices

I'm currently developing a microservice that is responsible for receiving messages from RabbitMQ. However, I am encountering an error message as follows: ERROR [Server] There is no matching event handler defined in the remote service. Event pattern: u ...

Encountering a Typescript error while attempting to extract state from a History object containing an enum property

My enum structure is as follows: enum values { first, second, } Within my component, I handle the history object like this: const { push, location: { state = {} } } = useHistory(); Additionally, in the same component within a useEffect hook, I have ...

Is there a way to verify useFormik functionality while the form is being submitted?

Below is the implementation of the Form component which utilizes the useFormik hook. While the component fulfills all my requirements, I encounter challenges when it comes to testing, especially during form submission. Form.tsx import { TextField, But ...

Error in AngularX TS: Trying to invoke a type that does not have a callable signature

Encountering an issue while working on a component, specifically during ng serve/build process. Please note that this error is different from any console errors, despite what some may think. The expected outcome is for the code to successfully build and ru ...