Adding a timestamp or hash as a request parameter for css or js files in the NextJS 12 build file can be accomplished by simply including "?ts=[timestamp]" in the file

It is important for me to be able to generate the following JavaScript and CSS file names with timestamps after building a NextJs application: ./path/file.js?ts=[timestamp] ./path/file.css?ts=[timestamp]

Answer №1

After some exploration, I came up with the following solution:

  1. To start off, create a file named _document.tsx and define a class that inherits from Document.
class StaticDocument extends Document {
  render () {
    return (
      <Html>
        <CustomHead />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}
  1. Next, prepare CustomHead which extends Head. I found certain functions within the library for the Head class and decided to override them: getDynamicChunks, getScripts, and getCssLinks.
(function...) 

In analyzing the code further, I pinpointed the sections responsible for creating links and introduced additional code featuring a timestamp: ('?ts=' + timestamp).

  1. Upon debugging, I discovered that _documents.tsx runs both during 'npm run dev' and the build process. However, the build process involving _document.tsx comprises of two distinct stages: a) building into the .next folder and b) execution of _document.js exclusively during the build process without being called during 'npm start'.

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

Steps for assigning a parameter to a general purpose function

Having a generic function named retrieve: function retrieve<T>(endpoint: string, id: string, /* etc */): T {} The goal is to define a function like retrieveUser, which binds the first parameter and specifies T. An attempt was made using Function.pr ...

Instead of retrieving documents, the MongoDB query is returning topology information

I am currently working with MonogDB and NextJS. My goal is to create an endpoint that returns all the users. However, I am encountering a strange response: { "_events": {}, "_eventsCount": 0 } My code for querying the database looks li ...

Naming Convention for Next.js Client/Server Components

There are instances where the distinction between client-side and server-side relationships may not be clear when using nextjs' app router, particularly with abstracts. How do you differentiate between client and server files/components? Do you us ...

Ways to check the functionality of the secondary tier in the api.send method

Currently, I am testing a function that involves returning a promise and subsequently calling the same function again at a second level. However, I am facing difficulties in accessing this second level of call. Below is the function code: itemToForm = () ...

Error message stating 'is not recognized' caused by Angular SharedModule

I have a navbar component that I've organized into a module called 'NavbarModule' so that it can be easily shared. My goal is to use this component in the 'ProductsListComponent'. However, even after properly importing and exportin ...

Preview links are not displaying correctly in LINE Messenger for a Next.js application despite having OGP settings configured

My Next.js application successfully generates URL previews for social media platforms using OGP settings, particularly for Facebook debugger and other platforms. However, I am facing an issue with LINE messenger and WhatsApp as they do not display any prev ...

After updating to version 11 of Next.js, encountered an error due to an unsupported file type: undefined

While attempting to load an image after updating Next.js to version 11 using the code below: import segmentLogoWhitePng from 'assets/images/my-image.png' I encountered the following error message: TypeError: unsupported file type: undefined (fil ...

An error occurred while trying to access the 'pop' property of an undefined value in next.js

view the project screenshot $ npm run build > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfb3babeadb1f2acabbeadabbaad9feff1eef1eef1">[email protected]</a> build > next build (node:31220) [DEP0148 ...

Combining TypeScript into HTML resulted in an error: Uncaught ReferenceError clickbutton is not defined

Attempting to create a basic CRUD frontend without the use of any frameworks. I am encountering an issue when trying to include a TypeScript file (index.ts) in my index.html, as the functions called within it are showing as undefined. I understand that bro ...

Guidelines on Delivering Images to Clients from Remote Storage using Next.js

Trying to figure out the best way to serve images from remote object storage is sparking some questions for me. In accordance with Next.js documentation, the recommendation is to load remote data into server components whenever it's feasible. This pr ...

Exploring Typescript's type narrowing capabilities through destructuring

This code snippet is encountering errors: type Example = { x: true, y: null, z: null } | { x: false, y: Error, z: null } | { x: false, y: null, z: { val: number} } function getExample(): Example { return { x: false, y: null, z: { val ...

Obtain a tuple of identical length from a function

I'm attempting to create a function that returns a tuple with the same length as the parameter tuple passed to it. Although I tried using generics, I am encountering an error when applying the spread operator on the result. My goal is best illustrate ...

Tips for storing information without using ngModel in template-driven methodology

Currently facing a dilemma where data needs to be saved to the database from Angular UI. The display format of tabular data changes dynamically based on dropdown selections, without having predefined model properties for binding. The question arises: How ...

Exploring the process of retrieving token expiration in TypeScript using the 'jsonwebtoken' library

Currently utilizing jsonwebtoken for token decoding purposes and attempting to retrieve the expiration date. Encountering TypeScript errors related to the exp property, unsure of the solution: import jwt from 'jsonwebtoken' const tokenBase64 = ...

Patience is key as we anticipate the parent component/module loading the data

Just a note: I am aware of the existence of APP_INITIALIZER, but it appears to only work in the top-level module (app.module.ts) of the application. I have a parent component that loads some data: In admin-area.component.ts: ngOnInit(): void { forkJo ...

Is localStorage.getItem() method in NextJS components behaving differently?

I'm working on my nextjs application and I wanted to utilize the power of localstorage for storing important data throughout my app. Within the pages directory, specifically in the [slug].tsx file, I implemented the following logic: export default fu ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

Creating distinct images for individual environments using Gitlab-CI AutoDevOps

When building Dockerfiles, ENV variables can be passed using --build-args. These variables are essential for NextJS, especially when dealing with static pages that require calling remote APIs. The challenge is that these variables are "Hard coded" within t ...

Tips for showing a temporary image placeholder during the loading process in Next.Js

When fetching images from Firebase with getStaticProps and displaying them using the next Image component, there is a delay in loading. Is it possible to show a placeholder until the images are fully loaded? ...

Template URI parameters are being used in a router call

Utilizing the useRouter hook in my current project. Incorporating templated pages throughout the application. Implementing a useEffect hook that responds to changes in the router and makes an API call. Attempting to forward the entire URL to /api/${path ...