最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to read the build ID of NextJS? - Stack Overflow

programmeradmin2浏览0评论

With NextJS, it's possible to create a build ID, according to the docs :

It's also possible to get it according to the last git version :

But the question is : how do I read this build ID? I'd like to display it inside the window console.

With NextJS, it's possible to create a build ID, according to the docs : https://nextjs/docs/app/api-reference/next-config-js/generateBuildId

It's also possible to get it according to the last git version : https://www.npmjs./package/next-build-id

But the question is : how do I read this build ID? I'd like to display it inside the window console.

Share Improve this question edited Jun 1, 2023 at 0:27 Yilmaz 49.8k18 gold badges216 silver badges270 bronze badges asked May 30, 2023 at 13:30 bdavidxyzbdavidxyz 2,5602 gold badges22 silver badges40 bronze badges 1
  • 1 @phd Because I also want to read the git mit/version SHA. – bdavidxyz Commented May 30, 2023 at 13:42
Add a ment  | 

4 Answers 4

Reset to default 2

I have not tested it, but I think you can try the old (I guess it's deprecated now, but it still should work) way of passing env vars through the env key in the config, like that:

const nextBuildId = require('next-build-id')

const buildId = nextBuildId({ dir: __dirname })

const nextConfig = {
  generateBuildId: () => buildId 
  env: {
    BUILD_ID_ENV: buildId
  },
};

And it will be available later as process.env.BUILD_ID_ENV

To use it in the client side ponent potentially you would have to name it as NEXT_PUBLIC_BUILD_ID_ENV, not sure about it.

this works in server ponent because that package uses fs

import buildId from "next-build-id";

console.log("next-build-id", await buildId());

proof of work:

From @Danila i got solution like this

const nextBuildId = require('next-build-id')

const nextConfig = {
  env: {
     NEXT_PUBLIC_BUILD_ID: nextBuildId.sync({
      dir: __dirname,
      describe: true
    })
  },
};

also working at client side by calling process.env.NEXT_PUBLIC_BUILD_ID

note: it wont work 'describe: true' wont work on vercel because .git not exist.

If anyone wants a simple solution, hires what i did.

function getBuildId() {
    const buildIdPath = path.join(process.cwd(), '.next', 'BUILD_ID');
    return fs.readFileSync(buildIdPath, 'utf8').trim();
}

Also if ever you are using it for integrating redis as cache.

const path = require('path');
const fs = require('fs');
const createClient = require('redis').createClient;

const CacheHandler = require('@neshca/cache-handler').CacheHandler;
const createLruCache = require('@neshca/cache-handler/local-lru').default;
const createRedisCache = require('@neshca/cache-handler/redis-strings').default;

function getBuildId() {
    const buildIdPath = path.join(process.cwd(), '.next', 'BUILD_ID');
    return fs.readFileSync(buildIdPath, 'utf8').trim();
}

CacheHandler.onCreation(async () => {
    const buildId = getBuildId();
    const localCache = createLruCache({
        maxItemsNumber: 10000,
        maxItemSizeBytes: 1024 * 1024 * 250 // Limit to 250 MB
    });

    let redisCache;
    if (!process.env.REDIS_URL) {
        console.warn('REDIS_URL env is not set, using local cache only.');
    } else {
        try {
            const client = createClient({
                url: process.env.REDIS_URL
            });

            client.on('error', (error) => {
                console.error('Redis error', error);
            });

            await client.connect();
            console.log(('hey12', buildId));

            redisCache = createRedisCache({
                client,
                keyPrefix: `next-shared-cache-${buildId}:`,
                // timeout for the Redis client operations like `get` and `set`
                // after this timeout, the operation will be considered failed and the `localCache` will be used
                timeoutMs: 5000
            });
        } catch (error) {
            console.log('Failed to initialize Redis cache, using local cache only.', error);
        }
    }

    return {
        handlers: [redisCache, localCache],
        ttl: {
            // This value is also used as revalidation time for every ISR site
            defaultStaleAge: process.env.NEXT_PUBLIC_CACHE_IN_SECONDS,
            // This makes sure, that resources without set revalidation time aren't stored infinitely in Redis
            estimateExpireAge: (staleAge) => staleAge
        }
    };
});

module.exports = CacheHandler;
发布评论

评论列表(0)

  1. 暂无评论