Configuring NextJs routes with multiple parameters

Seeking guidance on structuring files in Nextjs for handling multiple URL parameters. Can anyone offer advice?

The given URL structure is:

/api/upload?file=${filename}&fileType=${fileType}

This is the current file structure:

app 
   api
      upload
            [filename]
                      [fileType]
                                route.ts

Despite following this directory layout, encountering the following error:

- error No HTTP methods exported in 'C:\Users\Alex\Documents\GitHub\procore-new\app\api\upload\route.ts'. Export a named export for each HTTP method.

Below is the code snippet from the route file:

import S3 from "aws-sdk/clients/s3";

import { NextResponse } from "next/server";

interface IParams {
  filename: string;
  fileType: string;
}

export async function GET(request: Request, { params }: { params: IParams }) {
  const { filename, fileType } = params;

  const s3 = new S3({
    signatureVersion: "v4",
    region: "us-east-2",
    accessKeyId: process.env.ACCESS_KEY,
    secretAccessKey: process.env.SECRET_KEY,
  });

  const preSignedUrl = await s3.getSignedUrl("putObject", {
    Bucket: process.env.BUCKET_NAME,
    Key: filename,
    ContentType: fileType,
    Expires: 5 * 60,
  });

  return NextResponse.json({ preSignedUrl });
}

Here's the frontend request logic:

"use client";

import axios from "axios";

import { toast } from "react-hot-toast";

const ImageUpload = () => {
  const uploadPhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]!;
    const filename = file.name;
    const fileType = file.type;

    console.log(file, filename, fileType);
    const res = await axios(
      `/api/upload?file=${filename}&fileType=${fileType}`
    );
    const { url } = await res.data;

    const config = {
      headers: {
        "Content-Type": fileType,
      },
    };

    const upload = await axios.put(url, file, config);
    if (upload.status === 200) {
      console.log("Uploaded successfully!");
    } else {
      console.error("Upload failed.");
    }

    const s3FileUrl = `https://<nextjspractice>.s3.us-east-2.amazonaws.com/${filename}`;
    console.log("file url: ", s3FileUrl);
  };

  return (
    <input type="file" accept="image/png, image/jpeg" onChange={uploadPhoto} />
  );
};

export default ImageUpload;

Considering using the spread operator on the folder like [...params], unsure if that's the right approach. Any insights are highly appreciated!

Answer №1

Success! I have discovered the solution.

If you are utilizing [paramName] in your file structure within your app/(route)/route.ts and dealing with multiple params, try this approach:

Start by creating a folder that spreads the params object, for example: [...params], and inside it, create the standard route.ts file.

Within that file, destructure the params as shown below:

interface IParams {
  filename: string;
  fileType: string;
}

export async function GET(request: Request, { params }: { params: IParams }) {
  const { filename, fileType } = params;

This will give you an array of all the params, like so:

{ params: [ 'PeapodXTraceOne.png', 'image', 'png' ] }

Additionally, ensure your api request is structured as follows:

const res = await axios(`/api/upload/${filename}/${fileType}`);

Each param after the route name should be preceded by a '/'.

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

"Exploring the seamless integration of Next.js and Material UI for stunning web

I have encountered an issue while using Next.js and Material-UI(@mui/core) to build a website. Everything works perfectly when I run it with next dev, but the styles get messed up when using next build && next start. In addition to Material-UI, I ...

One efficient way to iterate through an object and modify its values in a single line of code

_shop: { [key: string]: string[] } = { fruits: ['Apple', 'Orange'], vegetables: ['Tomato', 'Onions'] } Can a one-liner code be used to modify the values of _shop and return it in a specific format? The desired outp ...

The React application, when built using `npm run build`, experiences difficulty loading image sources after deployment to App Engine

In my React frontend application, I have the logo.png file being loaded in Header.tsx as an img element like this: <img className={classes.headerLogo} src={'logo.png'} alt={"MY_LOGO"}/> The directory structure looks lik ...

Change validators dynamically according to conditions

Scenario: At the start, there is a single text box named Name1, a date picker called DOB1, and a check box labeled Compare. Both Name1 and DOB1 are mandatory. When the checkbox is clicked, two new form controls are dynamically included, named Name2 and DO ...

Having trouble setting up my Next.js application on Docker platform

I am currently working with a VPS running Ubuntu 22.04 and my goal is to create and run a Next.js application within a Docker container. Instead of having NodeJS installed directly on Ubuntu, I want the node:18-alpine image to handle all the necessary fun ...

Incorporating type declarations for a basic function that returns a wrapper function for other functions

In my vanilla JS code, I have a sophisticated function that is exported and I am attempting to create a .d.ts file for it. Unfortunately, my previous attempts at writing the .d.ts file have not been successful in passing the types from one stage of the fu ...

The Apollo client's GraphQL query encountered an unforeseen termination of the JSON input stream

I have customized my NextJS site with WP WooCommerce integration. By default, the query result only returns up to 100 items, but I have increased it to 1000 without any issue. When I send a request with a query like this: query MyQuery { products(fir ...

Display the number of objects in an array using Angular and render it on HTML

I am having trouble displaying the length of an array on my HTML page. No errors are showing up in the console either. Can someone help me figure out how to get the total number of heroes? HTML: <div *ngFor="let hero of heros"> <div>The tota ...

Jest assertions encountering type errors due to Cypress

After using react-testing-library and @testing-library/jest-dom/extend-expect, I decided to install Cypress. However, I now face Typescript errors on all my jest matchers: Property 'toEqual' doesn't exist on type 'Assertion'. Did ...

Can Bun automatically bundle my TypeScript files when I save them in VS Code?

Is it feasible for Bun to bundle my TypeScript upon saving a file in VS Code? The instruction manual suggests running bun run index.ts in the command line and including it in the package.json in this manner. However, I am unsure how to automate this proce ...

The Angular 4 application is unable to proceed with the request due to lack of authorization

Hello, I am encountering an issue specifically when making a post request rather than a get request. The authorization for this particular request has been denied. Interestingly, this function works perfectly fine with my WPF APP and even on Postman. B ...

Updating the data attribute of an object in HTML using Angular

I am trying to embed a PDF viewer inside a component. In order to dynamically update the PDF document within a sanitizer, I need to use an attribute with []. This works fine with images. <img src="assets/pic.jpg"/> <img [src]="'assets/pi ...

Is there a way to make an accordion close from a nested component in react?

I'm in the process of developing a page to update product information on an e-commerce platform using NextJS. On the individual item page, I have structured the image upload section within an accordion. After the images are uploaded, I want to reset t ...

Unable to upload picture in React, error message states "This file is not recognized as an image file"

While attempting to compile my project that includes images, I encountered an issue. When running yarn dev, most of the project compiles successfully except for the images. I keep receiving the following error message: Error: Image import "../assets/images ...

Using Rxjs to handle several requests with various headers

I have a specific requirement where, if hasProcessado == true, 10 additional requests should be made before issuing the final request. If the final request fails, 3 more attempts are needed. Furthermore, when sending the last request, it is essential to n ...

An API key was not included in your request. To proceed, please ensure your API key is included in the Authorization header

I encountered an error while using the checkout function with Stripe: API key not provided. Please include your API key in the Authorization header using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). Refer to https://stripe.com/doc ...

The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request. The API supports the use of @RequestPart and @RequestParam: @RequestPart("file") MultipartFile file; @RequestParam(value = "document-types", required = false) Set<String> documentTypes; My appro ...

Maintain Angular Dropdown Menu Open Across Page Refresh

I am currently working on an HTML/Typescript view that is connected to a SQL Database. Whenever there are changes made to the database, the entire webpage reloads. The issue we are facing is that we have dropdown menus on the page that clients want to rema ...

Is there a way to use Lodash to quickly return the same value if a condition is met using the ternary operator

Is there a condensed way to do this using Lodash? (or perhaps Vanilla JS/TypeScript) var val = _.get(obj, 'value', ''); Please note that var val = obj.value || ''; is not suitable as it considers 0 and false as valid but fal ...

What is the process for incorporating the jsnetworkx library into an ionic or angular 4 project?

When using any Ionic3 app service import * as jsnx from 'jsnetworkx'; The output error message is: Uncaught (in promise): Error: Cannot find module "lodash/lang/isPlainObject" Error: Cannot find module "lodash/lang/isPlainObject" at webpackMis ...