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

Next.js is throwing a TypeError because it is unable to convert undefined or null to an object

Whenever I try to run my project locally, I encounter the 'TypeError: Cannot convert undefined or null to object' error as shown in the screenshot below. I've attempted updating all the packages listed in package.json. Furthermore, I delete ...

Tips for verifying internet connectivity and accessing stored data in localstorage

I'm working on my home.ts file and I need to use localStorage items when the internet connection is offline. However, I am encountering numerous errors when trying to add an IF condition in my code. Specifically, I want to access the getItem method be ...

Unable to change the data type of the value within the object

I have developed a next.js application that uses MongoDB as the database. In my code, I am facing an issue where after clicking the submit button, all the data is displayed in a table. I have extracted specific data like product_unit and product_price sep ...

What is the proper type declaration for incoming data from the backend in my TypeScript code when using axios?

In the TypeScript code snippet provided, the type for 'e' (used in the function for form submission) has been figured out. However, a question arises if this type declaration is correct. Additionally, in the catch block, the type "any" is used fo ...

Error occurred while creating a new instance of a generic object

I´m encountering a TypeError: type is not a constructor when attempting to convert API data into Frontend DTOs. The transformation method is as follows: transform<T>(entities: any[]) { const tableDtos = new Array<T>(); for (const ent ...

Utilize ngx-filter-pipe to Streamline Filtering of Multiple Values

Need assistance with filtering an array using ngx-filter-pipe. I have managed to filter based on a single value condition, but I am unsure how to filter based on multiple values in an array. Any guidance would be appreciated. Angular <input type="text ...

What is the best way to include two class names within a single div using Next.js?

Struggling to include two different CSS classes into a single div element, I encountered some issues. For reference, here is a screenshot: https://i.stack.imgur.com/UuCBV.png https://i.stack.imgur.com/sHNwq.png My code snippet looks like this: blog.js ...

Utilizing NextJS to fetch JSON data from the public directory

I am having trouble importing a globe.json file from my public folder. When I try to import it, I get the error message Module not found: Can't resolve '/globe.json' This is how my files are structured currently: public globe.json src ...

Using private members to create getter and setter in TypeScript

Recently, I developed a unique auto getter and setter in JavaScript which you can view here. However, I am currently unsure of how to implement this functionality in TypeScript. I am interested in creating an Object Oriented version of this feature if it ...

Having trouble with uploading images on Amazon S3 and sharing them on Facebook? Learn how to set the correct meta tag "og:image" in Next

As I work on coding to enable sharing my website page on Facebook, I have utilized meta tags for open graphs. Previously, the images were stored on the server and linked in the meta tag like this: <meta key="og:image" property="og:image" content ...

`Nextjs customizes the position of locales`

Currently implementing i18n translation in my project, the default root appears as follows: https://example.com/en/business/transaction Is it possible to customize the root to appear as: https://example.com/business/en/transacation Thank you. ...

Unexpected behavior with React's radio buttons and state not behaving as anticipated

Although I've come across similar questions regarding React components with radio buttons, I'm facing an issue where my component is not behaving as expected... const availableClasses = { peasant: { name: "Peasant", cost: 0, ...

What is the process for incorporating personalized variables into the Material Ui Theme?

In the process of developing a react app with TypeScript and Material UI, I encountered an issue while attempting to define custom types for my themes. The error message I received is as follows: TS2322: Type '{ mode: "dark"; background: { default: s ...

What is the best way to send an enum from a parent component to a child component in

I'm trying to send an enum from a parent component to a child component. This is the enum in question: export enum Status { A = 'A', B = 'B', C = 'C' } Here's the child component code snippet: @Component({ ...

Is there a way to set up a global web socket in NextJs?

I recently completed a tutorial on setting up a socket chat app, which I found at the following link: tutorial link. While I have successfully managed to get the system up and running, I'm facing an issue with exporting the front-end socket from the i ...

Updating a value in an array in Angular using the same ID

I have an array of buildings that looks like this: const buildings = [ { id: 111, status: false, image: 'Test1' }, { id: 334, status: true, image: 'Test4' }, { id: 243, status: false, image: 'Test7' }, { id: 654, stat ...

Issue ( Uncaught TypeError: Trying to access a property of undefined ('data') even though it has been properly defined

One of my custom hooks, useFetch, is designed to handle API data and return it as a state. useFetch: import { useState, useEffect } from "react"; import { fetchDataFromApi } from "./api"; const useFetch = (endpoint) => { const [d ...

How can I store unique and only selected checkbox values in an array using Angular?

I need assistance with creating an array from three checkboxes. The array should only contain the values of the checked checkboxes and should not include duplicates. I have attempted to achieve this functionality, but the values are still being added rega ...

How to prevent duplicate database entries in Angular forms?

Currently, I am working on a project using Angular and TypeScript. The goal is to retrieve a list of users from an API and allow for the addition of new users. However, I am struggling with determining how to verify if a user with a specific name already e ...

Angular 5 Image Upload - Transfer your images with ease

I am having trouble saving a simple post in firebase, especially with the image included. This is my current service implementation: uploadAndSave(item: any) { let post = { $key: item.key, title: item.title, description: item.description, url: '&a ...