Search code examples
javascriptnext.jsstatic-site-generation

Next.js how to ignore a complete folder in app?


On next 13, app/api folder creates an error during build when nextConfig.output is "export".

In my project, I need different build type depending on environnement variable.

Any way to ignore "api" folder during build when "output" is "export" ?

When I run build with nextConfig.output as "export" I got following error:

Export encountered errors on 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 to reproduce this error https://github.com/zeckaissue/next-export-api-crash


Solution

  • I found a workaround with ignore-loader. But maybe there is a better way to achieve my goal with a built-in feature of next.js

    Here is my updated next.config.js

    /** @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;