What is the best way to manage files in production using Next.js?

I've been working on a Next.js app for file exchange and am looking to deploy it. During development, the app saves dropped files in the root public folder and retrieves them from there using the <a> tag with an href attribute of uploads/{filename}. While this setup works well in development, it's not as effective in production.

I'm aware that when running npm run build, Next.js takes files from the public folder, meaning any files added during runtime won't be served.

My main question is whether there are alternative methods for persistent file storage in Next.js other than relying on third-party services like AWS S3.

Answer №1

Subsequent in framework environment is FrameworkX, so if your hosting provider allows you to create a persistent drive and connect it to your project, then you can achieve this:

For example, in pages/api/saveData.ts:

import { writeFileSync } from 'fs';
import { FrameworkApiRequest, FrameworkApiResponse } from 'framework';

export default async function handle(request: FrameworkApiRequest, response: FrameworkApiResponse) {
    const { filePath = null } = request.query;
    if (!filePath) {
        response.status(400).json({ message: 'no file path provided' })
    } else {
        // enter your data here
        const data = Date.now().toString();
        writeFileSync(`/storage/${filePath}.txt`, data);
        response.json({
            filePath,
            data
        })
    }
}

/storage is compatible with most hosting providers (including FrameworkX itself), but these files may be lost during the next update; instead, consider using your connected drive path

pages/api/readData.ts

import { readFileSync } from 'fs';
import { FrameworkApiRequest, FrameworkApiResponse } from 'framework';

export default async function handle(request: FrameworkApiRequest, response: FrameworkApiResponse) {
    const { filePath = '' } = request.query;
    if (!filePath) {
        response.status(400).json({ message: 'incorrect' })
    } else {
        response.send(readFileSync(`/storage/${filePath}`));
    }
}

Check out a live demonstration:

fetch('https://yourproject.vercel.app/api/writedata?filePath=test')
.then(res => res.text()).then(res => console.log(res)).then( () => 
fetch('https://yourproject.vercel.app/api/readdata?filePath=test'))
.then(res => res.text()).then(res => console.log(res))

Answer №2

During buildtime, Next.js supports file storage; however, it does not support runtime file storage. To meet your file upload needs, AWS S3 is recommended as the best solution.

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

Masked input fails to accurately capture data

When utilizing VueJS together with the Quasar framework. An issue arises when using a masked q-input, where the value becomes incorrect after a toggle. For instance, if we start with a default value of: officeNum: 654321, mobileNum: 12345678, Then our ...

Managing extensive amounts of data with server-side scripting in a Datatable

I am exploring the use of the datatable plugin to effectively manage a large amount of data. Currently, I am interested in implementing "server side processing in datatables" with the help of server-side scripting. Since I have limited experience with AJA ...

How can socket listener be dynamically added in node.js with socket.io?

Assuming you have a basic socket.io configuration set up: var app = require('http').createServer().listen(80,'127.0.5.12'), io = require('socket.io').listen(app); session = require('./local_modules/session.js'); / ...

Best practices for distinguishing between template and style for mobile and desktop in Angular 2 components

Creating templates for mobile and desktop requires unique designs, but both share common components. To ensure optimal display on various devices, I plan to store separate templates and designs for mobile and desktop in distinct files. The goal is to inc ...

Embed the contents from a URL within an HTML document

I am currently in the process of developing an application using Node.JS and Express v4. My chosen template engine is Nunjucks. One of the routes I have set up for my app is the (widget) route, which is being rendered through Express with this code: app.g ...

Angular HTML prints only halfway down the page when document is printed

While utilizing document.write(), I encountered an issue when printing the contents of an object specifically formatted for a printer. The text started printing only halfway down the page. I can successfully print the screen without any problems, which ma ...

Creating Hbbtv applications with the help of a Firefox Addon

My curiosity lies in creating hbbtv apps and I am eager to learn how to run and test a complete hbbtv application package, specifically a videoplayer with multiple html pages, utilizing the FireHBBTV plugin on Firefox. Despite my extensive search efforts ...

Using a for loop in Flot to display data from a JSON file

I am working on creating a dynamic flot graph that will adjust based on the data provided. The information for my flot graph is in JSON format, and here's an example of the dataset: { "total":[[1377691200,115130],[1377694800,137759],[1377698400,1 ...

Tips for allowing specific tags using Google's Caja HTML Sanitizer in a node.js environment

I'm currently utilizing the npm module Caja-HTML-Sanitizer with node.js. Although I am able to sanitize the HTML input using the sanitizer() function, I am unsure of how to implement a whitelist in order to restrict only certain tags (e.g. p br stron ...

`React Hook Challenges: Finding a Solution`

I've been experimenting with React to create a basic recipe management application and I've encountered a problem that I haven't been able to solve yet. import { useParams, useHistory, Link } from "react-router-dom"; import useFetc ...

Discovering specific keywords within HTML tags and performing replacements using jQuery

I am searching for specific strings within my HTML code, and if I find them, I want to replace them with nothing. For example: HTML: <img src=`javascript:alert("hello ,world!")`> My goal is to locate keywords like javascript, alert, etc, within H ...

Tips on implementing a script injected through the JS console to update form data in an Angular webpage and ensure that the changes are successfully saved

I am currently working on enhancing an existing electron app integrated with Angular. The main goal is to inject a script once the application is loaded in order to add a hotkey for efficiency. This hotkey should automatically click an edit button, input s ...

Decoding the information received from Socket.IO within the Flash client

When utilizing server node.js and module Socket.IO, data transmission is handled as shown below: var tests = [555, 777]; client.send("Test string"); //first message client.send({tests:tests}); //second message If the data sent is a text string (fi ...

Switch statements within switch statements

Currently encountering an issue where nothing is showing up. Assistance needed, please... function getTotal() { var service = prompt("What service are you interested in? ", " "); var options = prompt("How often would you like the service? ", " "); var c ...

Managing the clearing of a view component in React or Vue.js

In my project, I have a container component that handles all the business logic, ajax requests, and data management. This container component has child components to which it passes data and methods as props. For example, there is a "CommentForm" compone ...

Text placeholder in form fails to display properly when radio buttons are added

I've encountered an issue with the script below while attempting to use placeholders. It breaks when radio buttons are added. What could be causing this problem? var labels = document.querySelectorAll("label"); var i = labels.length; while (i--) { ...

The navigation bar on the web app is functioning properly on Android devices but experiencing a CSS problem on

My Nextjs web app includes a navbar with a hamburger menu, logo, and avatar. The navbar functions perfectly on desktop in Chrome, Mozilla, Brave (in developer tools mobile mode), and on Android phones using Chrome. However, when accessed from an iPhone X, ...

Guide on displaying paginated data retrieved from an API response in React Native console

After trying several tutorials, I still couldn't resolve my issue. This is where I am stuck in my code const [data, setData] = useState([]) useEffect(() => { getData() }, []) const getData = async () ...

List of nested objects converted into a flat array of objects

Looking to transform a data structure from an array of objects containing objects to an objects in array setup using JavaScript/Typescript. Input: [ { "a": "Content A", "b": { "1": "Content ...

Exploring the Differences Between Meteor JS Backend and Express JS

I have a basic understanding, but I'm interested in learning more: I came across a comparison on Stack Overflow that likened Meteor JS and Express JS to oranges and potatoes. My current understanding is that Meteor JS is full stack (Front End, Back E ...