Is there a way to exclude an entire folder from being processed in Next.js application?

When the "output" in nextConfig is set to "export", an error occurs in the app/api folder during the build process on the 13th.

In my project, I require different build types based on environment variables.

Is there a way to exclude the "api" folder from the build when the "output" is set to "export"?

Upon running the build with nextConfig.output as "export", the following error is encountered:

Export encountered errors on the following paths: /api/revalidate/route: /api/revalidate

src/app/api/revalidate/route.ts file

import { NextRequest, NextResponse } from 'next/server';
import { revalidateTag } from 'next/cache';
 
export async function GET(request: NextRequest) {
  const tag = request.nextUrl.searchParams.get('tag');
  if(tag){
    revalidateTag(tag);
  }
  return NextResponse.json({ revalidated: true, now: Date.now() });
}

Next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: process.env.NEXT_OUTPUT_MODE,
};

module.exports = nextConfig;

Reproducible repository

Here is a repository link to reproduce this issue https://github.com/zeckaissue/next-export-api-crash

Answer №1

I managed to find a workaround using the ignore-loader package. However, I am wondering if there is a more efficient way to accomplish my objective by utilizing a built-in feature of next.js.

Below is the updated version of my next.config.js file:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: process.env.NEXT_OUTPUT_MODE,
  /**
   *
   * @param {import('webpack').Configuration} config
   * @param {import('next/dist/server/config-shared').WebpackConfigContext} context
   * @returns {import('webpack').Configuration}
   */
  webpack: (config) => {
    if (process.env.NEXT_OUTPUT_MODE !== "export" || !config.module) {
      return config;
    }
    config.module.rules?.push({
      test: /src\/app\/api/,
      loader: "ignore-loader",
    });
    return config;
  },
};

module.exports = nextConfig;

Answer №2

To utilize the ignore feature in your Next.js setup, you need to modify the next.config.js file. If you haven't created a configuration file yet, go ahead and create one now. Simply open the next.config.js file and include the code snippet provided below:

module.exports = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.module.rules.push({
        test: /YOUR FOLDER NAME\/.*/,
        loader: 'ignore-loader',
      });
}

Answer №3

For NextJS 14.2.8 with the latest App Router update and API route handlers, you can implement the following solution:

  1. Start by installing the ignore-loader:

    npm install --save-dev ignore-loader

  2. Add the ignore-loader configuration to your next.config.js file:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export',
  webpack: (config) => {
    if (process.env.NODE_ENV == "production") {
      config.module.rules.push({
        test: /app\/api\/.*/,
        use: 'ignore-loader',
      });
    }
    return config;
  },
}

module.exports = nextConfig;

When running next dev in development mode and next build in production mode, this setup allows you to utilize API routes during development but exclude them when generating the static site.

Keep in mind that NextJS will still display /api/... routes during the static site build process. However, the actual /api/ files will not be included in the final build.

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

Having trouble interacting with the "Continue" button on PayPal while using Selenium

Recently, I have encountered an issue with automating payments via PayPal Sandbox. Everything used to work smoothly, but now I am unable to click the final Continue button no matter what method I try. I have attempted regular clicks, using the Actions cl ...

How can I convert a string number with leading zeros into a string in a node.js environment?

When rendering a page, I pass the id as a string (e.g. 001, 002) but at the client side, I receive it as a number (e.g. 1, 2). res.render('leafletDemo',{id:userID,latitude:latitude,longitude:longitude}); Is there a way to keep the id as a str ...

AngularJS Chart.js Element Instances

Feeling a bit stuck here, I'm importing JSON data into a smart table and creating charts based on that table. I want to implement cross-filtering so that when a filter is applied, the chart updates based on the filtered data in the table. The chart s ...

Organizing a Collection of Likes within an AngularJS Service

I have a like button on my profile page that, when clicked, should add the user's like to an array and store it in the database. Within my profile controller, I have the following code: $scope.likeProfile = UserService.likeProfile(loggedInUser,$stat ...

Jest tests are failing because React is not defined

I am attempting to implement unit tests using Jest and React Testing Library in my code. However, I have encountered an issue where the tests are failing due to the React variable being undefined. Below is my configuration: const { pathsToModuleNameMapper ...

Step-by-step guide for properly transferring PHP MySQL data to ChartJs

I am looking to create bar charts and pie charts using ChartJs, with data fetched from php and mysql. Specifically, I want to generate a bar chart that illustrates the statistics of male and female students, along with the total number of students. The des ...

Is employing setTimeout a legitimate technique for circumventing a stack overflow issue when implementing callbacks?

Let's imagine a scenario where I deliberately create a complex sequence of callbacks: function handleInput(callback) { ... } function fetchData(url, callback) { ... } function processResponse(callback) { .... } function updateDatabase ...

Updating all the direct components within the corresponding category with jQuery

Here is the HTML content I am working with: <li class="info"> info<li> <li class="other"> info<li> <li class="other"> info<li> <li class="Error"> error<li> <li class="other"> error<li> < ...

Expand your dropdown options with a Popup Input feature in the ComboBox to seamlessly add a 'New Option'

Hello there! I am currently learning, so please be patient with me. Currently, I am in the process of developing a web application for a product management system. The company I work for purchases products from multiple vendors, both through wholesale and ...

Transferring an Applescript list to ExtendScript in Javascript as an array for use in InDesign

Situation Background I have a large number of Applescripts (AS) that designers rely on in InDesign to streamline production workflows. These AS scripts handle a lot of OS interactions that JavaScript cannot replicate, so transitioning away from AS is not ...

Tips for identifying the version of a package that is installed using a package-lock.json file containing lockfileVersion = 3

After upgrading from Node 16 (npm 8) to Node 18 (npm 9), I noticed a difference in the structure of the package-lock.json files. Files generated with npm 8 have a lockfileVersion: 2, while those generated with npm 9 have a lockfileVersion: 3. The changes a ...

Issues with form submission and JavaScript functionality have been detected in Internet Explorer, Firefox, and Safari, but are functioning properly in Chrome

Hey there! I've encountered a puzzling issue with a form I've created. It's programmed to determine the next page to redirect to using JavaScript after submission. Oddly enough, everything functions perfectly when I test it out in my IDE (C ...

Adding data to a pre-made JavaScript file template to create a fresh document

In my web application, I have a form with multiple inputs: <form action=""> Title1:<br> <input type="text" name="title1"> <input type="text" name="title1Description"> <br> Title2:<br> <input t ...

Bootstrap's square-shaped columns

I would like to implement a grid of squares for navigation purposes. By squares, I mean that the colored areas should have equal width and height. Currently, I have achieved this using JavaScript, but I am interested in a CSS-only solution. My project is ...

How can I enhance this conversion function from an Array to an Object in JavaScript?

Looking to construct an object consisting of empty arrays using values as keys. const CATEGORIES = ['apple', 'banana', 'orange'] generateCategoryObject() === { apple: [], banana: [], orange: []} function generateCategoryO ...

Steps to halt webkit animation within a div located inside a circle:

I have a series of nested circle divs, and I want to give them a pulse animation. The issue is that the text container is within one of these circles, causing the animation to apply to the text as well. I am unable to move the text container due to potenti ...

Send back alternate HTML content if the request is not made via AJAX

Last time I asked this question, I received several negative responses. This time, I will try to be more clear. Here is the structure of a website: Mainpage (Containing all resources and scripts) All Other pages (HTML only consists of elements of that ...

What is the best method for locating the ID of a specific element tied to a dynamically generated button that presents profile information using javascript?

My goal is to show unique user information when the user hovers over a button. This information is contained in a specific div element with an ID that corresponds to the button being hovered over. The challenge I am facing is extracting the ID of the info ...

Retrieve all links with the class "execute" and list them below

Looking to extract links that start with <a class="execute" href=" from https://bitbucket.org/alceawisteria/ostr/issues and then showcase them below in the existing HTML document. Can this be achieved using JavaScript? (If not, what ...

Is there a way to utilize JavaScript in order to trigger a CSS animation to occur at a designated time during a video

I have a cool animated image element that I want to play at a specific point in time during a video using JavaScript. I'm not sure how to make it happen, but I know the .currentTime property could be the key. My goal is for the animation to only play ...