admin管理员组

文章数量:1401849

I'm trying to cache a large list of strings(names) on app start so that I don't have to build it everytime I receive an api request to return it.

I tried two ways:

METHOD NO. 1

// my util function to create names
function getDynamicNames() {
 return Math.random()+'name';
}

// next.config.ts

export let stars = []

async () => {
    const nextConfig = {
        // output: 'export', // Outputs a Single-Page Application (SPA)
        distDir: 'build', // Changes the build output directory to `build`
    }
    
    let i = 0;
    while (i < 1000000) {
        stars.push(getDynamicNames());
    }

    return nextConfig;
}

I get an empty array:

// api/test/route.ts
export const GET = () => NextResponse.json({
    status: 'success',
    message: 'Server is running...',
    data: stars
}, {status: 200})  // data -> []

METHOD NO. 2

I get an empty array as well, and yes the register function does run:

// instrumentation.ts

export let stars = []

export async function register() {
    let i = 0;

    while (i < 1000) {
        stars.push(getDynamicNames());
        i += 1;
    }
}

What is the correct way to cache values on server startup in nextjs

本文标签: nextjscaching values on app start in nextJscannot mutate a variableStack Overflow