What is the best way to access query string parameters within NextJS middleware?

In the context of NextJS middleware, I have successfully obtained the nextUrl object from the request, which includes details like the pathname. However, I am now wondering how to extract query string parameters directly within the middleware. Although I could manually parse the string returned by href, I would like to know if these parameters are available in a separate object.

For example:

export const middleware = (request) => {
  const { nextUrl: { query } } = request;
  ...
};

Assuming query contains:

{
  param1: 'foo',
  param2: 'bar',
  etc.
}

Answer №1

nextUrl object already contains searchParams, which is a valid instance of URLSearchParams.

An example of how to use it:

export function middleware(req: NextRequest) {
    if(req.nextUrl.searchParams.get('flag')) {
        return NextResponse.rewrite('/feature');
    }
}

Answer №2

Building on @j-cue's insight, I also made the discovery that you can extract the search data from the nextUrl.

For instance:

export const middleware = (request) => {
  const { nextUrl: { search } } = request;
  const urlSearchParams = new URLSearchParams(search);
  const params = Object.fromEntries(urlSearchParams.entries());
};

Answer №3

Starting from version 13.4 of Next.js, you are able to extract search parameters directly from the URL like this:

export const GET = async (request, { params }) => {
   try{
        
        // Path Params can be accessed through the {params} object
        // To extract search params, follow this example:
        // URL path: `/api/prompt/${post._id.toString()}?type=DELETE`
        // The search params [type, method] for the above URL

        const {type, method} = Object.fromEntries(request.nextUrl.searchParams);
        console.log(type, method);
        if(type === "DELETE" && method === "GET"){
            // Perform certain action based on the parameters
        }

        return new Response("Action performed", {status: 200});
   }
   catch(err){
    console.log(err);
   }
}

Answer №4

If you're looking to retrieve it from a specific source, consider using this method:

let searchParams = new URLSearchParams(window.location.search);
let queryParams = Object.fromEntries(searchParams.entries());

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

The unexpected (302) error is encountered when attempting to use Oauth with next-auth

I've been working on developing a website that supports Google sign-in using nextJS. However, I'm encountering persistent errors after clicking the sign-in button. Here's the current Home Page of my website. This is the error image that ke ...

The jQuery ajax function functions flawlessly on a local environment, but encounters issues when used on a

After spending the entire day researching this issue, it appears to be a common problem without a solution in sight. The challenge I am facing involves using jquery's $.ajax() function to update database values through a service call. While it works ...

How to remove every instance of an item in an array based on its unique identifier using JavaScript

Is there a way to clean up an array of objects by removing duplicates with the same id? In this case, I only want to keep the object with id 1. This is my approach: let data = [{ "selected": true, "id": 3, "ProductName": "Aniseed Syrup", ...

Utilizing Vue.js to initiate a server request with vue-resource

Seeking guidance on performing a server call using vue-resource. I'm unsure about how to set the header and send data via Vue.$http.post Vue.$http.post('http://url/', { email: 'foo', password: 'bar' }, { headers: { ...

In Next.js, the elements inside the div created by glider-js are not properly loaded

I'm currently working on setting up a carousel in nextjs using the data retrieved from an API and utilizing glider-js for this purpose. However, I'm facing an issue where the div created by glinder-js does not include the elements that are render ...

Discovering hidden Mixed Content problems on a secured website can be a challenging task

After deploying a simple PWA application on the NGINX server, which was created using Vue CLI, I decided to use hash mode instead of history mode for the Vue router. Even though the website is secure: I am encountering the following errors and I'm n ...

The Cross-Origin Resource Sharing (CORS) problem doesn't seem to be evident when sending a Postman GET request to Passport.authenticate(), but Nextjs is encountering issues when trying

I've been working on implementing Google Login with a Next.js frontend and an Express.js backend. I followed this tutorial. Using the URL http://localhost:5200/auth/google, I expect to receive the same response as when using Postman: <title>Sig ...

Positioning Images in Tailwind Modals

I'm currently working on building a modal using Tailwind in Vue, but I've run into some challenges with aligning the elements inside the modal as desired. I've experimented with removing certain Tailwind classes and have tried implementing ...

Encountering the error "gapi-script causing a ReferenceError: window is not defined in Next.js"

Despite trying numerous solutions, I continue to encounter the error shown in the screenshot below... puzzled as to why? Server Error ReferenceError: window is not defined This error occurred during page generation. Any console logs will be visible in the ...

What could be causing the hover effect to not work on the cards in my Svelte component? (HTML+CSS)

Greetings everyone! This is my debut post on this platform, and I'm in urgent need of assistance as I am relatively new to the world of programming. I've been trying tirelessly to implement a hover effect on these cards, but for some reason, it ...

Utilize Vue.js to sort by price bracket and category

Hello, I am currently new to working with Vue.js and I am attempting to create two filters - one for price range and the other for genre. Any guidance or assistance would be greatly appreciated. Below is a snippet of my code: ul class="filter-wrapper"&g ...

Can someone explain why Array.from(classList)[0] is not changing to 'className'?

HTML Design <div class="custom-container color-red"> <h3>Hello, I am a customized container</h3> </div> Javascript Logic let element = document.getElementsByClassName('custom-container')[0]; let clas ...

How to assign a global variable in Angular 2 from within a promise

I have encountered a strange issue while trying to assign a response to a global variable inside an observable. Here's the logic of my program: Fetch the latest playlists IDs from elastic search (using a type definition file for elastic search). T ...

Navigation bar failing to show all content on Safari web browser

When navigating to this website, http://www.togethermutualinsurance.co.uk, using any browser except for Safari on Windows, the menu displays correctly. However, in Safari, the title of the menus and submenus with images does not display properly. Despite ...

When using multer to upload a file, the issue of req.files being undefined may

I am currently working on a Node.js Application using Express.js 4 that involves uploading an image. I opted to utilize the multer module for this task, but encountered an issue with accessing the uploaded file via req.files. Below is the relevant portions ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

Vue.JS - Dynamically Displaying Property Values Based on Other Property and Concatenating with

I have a reusable component in Vue.js called DonutChart. <donut-chart :chartName="graphPrefix + 'PerformanceDay'" /> The value of the property graphPrefix is currently set to site1. It is used as part of the identifier for the div id ...

Retrieving time zone using offset with javascript

I am looking for a way to schedule time-based events on my server operating in UTC time. For the user interface, I need to input 2 parameters: The local time when the scheduled event should trigger The timezone offset Instead of displaying timezone n ...

Receive the Navigating event upon a new browser window opening with the help of the WebBrowser control in JavaScript

In my C# / .NET 4 project, I have a form containing a WebBrowser component that loads an external web page. An event handler is connected to the Navigating event which usually works well. However, there is an issue when a specific part of the loaded websi ...

Retrieve the final ID of a dynamic div

Unable to find a solution, I am attempting to retrieve the ID of the most recently created div on the page. The code I have been using with .last() doesn't seem to be functioning correctly. My syntax may be incorrect, as I can't seem to extract a ...