Ways to retrieve files that are not located in the public directory in Next.js

I'm currently working on a project using Next.js and storing files in the root directory under /uploads/qr/myimage.png. How can I access this file within the project? I attempted to create a route /api/getImg/route.js dedicated to serving image files, and included the following code:

import fs from 'fs';
import { NextResponse } from 'next/server';
import path from 'path';

export async function GET(req) {
  const { searchParams } = new URL(req.url);
        const id = searchParams.get("id");
  const imagePath = path.join(process.cwd(), 'uploads', 'qr', `${id}.png`);

  try {
    const data = fs.readFileSync(imagePath);
    return NextResponse.send(data);
  } catch (error) {
    console.error(error);
    return NextResponse.send('Image not found');
  }
}

Unfortunately, I encountered an error that reads:

next_dist_server_web_exports_next_response__WEBPACK_IMPORTED_MODULE_1__.default.send is not a function

Answer №1

After some experimentation, I have managed to solve the problem. The key was to send the response in a different format.

import fs from 'fs';
import { NextResponse } from 'next/server';
import path from 'path';

export async function GET(req) {
    const { searchParams } = new URL(req.url);
    const id = searchParams.get("id");
    try {
        // Read the image file from the uploads/qr directory
        const imagePath = path.join(process.cwd(), 'uploads', 'qr', `${id}.png`);
        const fileContents = fs.readFileSync(imagePath);

        return new NextResponse(fileContents, { status: 200, headers: new Headers({ "content-type": "image/png", }) })
    } catch (error) {
        console.error('Error serving image:', error);
        return NextResponse.json(error)
    }
}

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

Alter the arrow to dynamically point towards the location of the click source

I am currently working on creating a popover dialog that should point to the element triggering its appearance. The goal is for the arrow to align with the middle of the button when clicked. While I am familiar with using CSS to create pointing arrows, th ...

How can an HTML5 application be configured to enable access to intranet and local files?

It's a known fact that accessing the local path of a file added using a file input field or drag-and-drop is not possible even with the new FileAPI. Whether this limitation is good, bad, or ugly is not up for debate. The FileAPI specs clearly state th ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

Tips on customizing the appearance of mat-card-title within a mat-card

Is there a way to truncate the title of a mat card when it overflows? I tried using the following CSS: overflow:hidden text-overflow:ellipsis white-space: nowrap However, the style is being overridden by the default mat-card style. I attempted to use mat ...

Ways to connect images located outside of the Next.js project directory

Currently, I am working on a project that utilizes node.js and express for the back-end, as well as next js for the front-end. One of the features of this project is a form where users have the ability to create new products, each accompanied by an image. ...

Utilizing JSONLOADER in Three.js allows for efficient loading and

Currently, I am using JSONloader in three.js to load models and it works perfectly. However, I am struggling to find detailed steps or documentation on how to preload textures (which are images) in order to create an interactive feature where I can switc ...

What is the best way to create a selection input using buttons and save the chosen option in the state?

Check out this snippet showcasing 3 buttons const [role, setRole] = React.useState('') const [active, setActive] = React.useState(false) <Grid container spacing={1}> <Grid item xs={4}> <Button variant='plain&apos ...

Display the contents in a textarea with modal, not as a string

I'm currently working on implementing a modal overlay window with simplemodal that will display the contents of a text area. My goal is to show the rendered output rather than just the string value. For example, if a user enters HTML or includes an im ...

A step-by-step guide on integrating vuetify-component into codeceptjs

When attempting to write tests using codecept.js, I am facing difficulties accessing the vuetify components. <v-layout> <v-flex xs7> <v-text-field ref="video1min" v-model="video1min" :rules=" ...

Facing issue with receiving uploaded files in Spring controller

I am looking to upload a .txt file and then process it in my controller. Below is the code snippet from my .jsp file containing the form: <form id="uploadForm" action="contact/importContacts" method="POST" enctype="multipart/form-da ...

A guide to incorporating a textview into a React application using the Google Maps API

Wondering how to incorporate a textview within a react-google-maps component? Successfully setting up a Google map page in React using the react-google-maps API, I've managed to insert markers and link them with polylines. import React from "react"; ...

Disabling 'Input Number' feature is ineffective in Firefox browser

Is there a way to prevent the input value from changing when the up or down arrow is held, even if the input is disabled? I want to retain the arrows without allowing this behavior on Firefox. Give it a try: Press the up arrow. After 5 seconds, the input ...

Encountering an issue with Nextjs pagination when it comes to the

Trying to utilize the react-paginate package and encountering an error while attempting to access the pathname. Below is a snippet of my code: const paginationHandler = (page) => { const currentPath = location.pathname; const currentQue ...

Learn the secrets of displaying a pop-up alert message seamlessly without interrupting the page's rendering process. Additionally, discover how to effortlessly refresh a chart every

I need to display a pop-up if the value is less than 3. I have tried using the alert function, but it causes the page to not render. How can I show the pop-up without blocking the page and refresh the chart every 30 seconds? <script> ...

Using Fullcalendar Moment to retrieve the current time plus an additional 2 hours

Trying to tackle this seemingly simple task using moment.js in conjunction with Fullcalendar. My goal is to retrieve the current time and then add two hours to it. Within the select method (or whatever terminology you prefer), I currently have: select: f ...

Guide on displaying the AJAX response within an HTML or JSP element pulled from a database

description of image 1description of image 2How can I display an AJAX response from a database (map) on a JSP screen? I am able to retrieve the response in the browser console but unsure how to visually render it on the JSP page, like in a table or any ot ...

getting value of object property using a function that is located within the same object

I am attempting to access the 'context' property (or specifically 'context.settings') from within the 'ready' function in the same object. I am uncertain of the correct syntax to achieve this. Below is the code snippet: modu ...

If the Request does not recognize the OAuth key, generate a fresh new key

I am working with a React Native Frontend and an Express.js backend. The backend makes calls to a 3rd party API, which requires providing an OAuth key for the user that expires every 2 hours. Occasionally, when calling the API, I receive a 400 error indi ...

How can you verify user identity in Firebase when making a call to a cloud function on a

I have integrated Firebase into my React Native app, and I have only enabled anonymous login feature. Currently, I am attempting to invoke a Cloud Function from the app without utilizing the firebase SDK. Instead, I intend to make the call using axios. De ...

Leveraging the back button in an AngularJS Mobile SPA

Utilizing AngularJS for my Single Page App (SPA), I am currently exploring the most effective way to handle the back button functionality on mobile devices. My setup involves a single JavaScript file, one HTML page, and no partials. The content is reveale ...