Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cache-control header in getInitialProps() in NextJs

I need to set Cache-Control header with a dynamic value in getInitialProps method. I tried the below.

if(context.res){
    context.res.setHeader('Cache-Control','My-Cache-Control');
    context.res.setHeader('My-Header','My-Value');
}

But it looks looks like NextJs is overriding the header value before sending the response. Below is the cache-control header value in response header in browser.

Cache-Control: no-store, must-revalidate
My-Header: My-Value

Let me know if anything is missing.

like image 475
Cyril Sadasivan Panicker Avatar asked Jan 10 '18 10:01

Cyril Sadasivan Panicker


People also ask

How do I use getInitialProps in NextJS?

Make sure the returned object from getInitialProps is a plain Object and not using Date , Map or Set . For the initial page load, getInitialProps will run on the server only. getInitialProps will then run on the client when navigating to a different route via the next/link component or by using next/router .

Can I use getInitialProps with getServerSideProps?

js - You can not use getInitialProps with getServerSideProps.

Is getInitialProps deprecated?

Addition of getServerSideProp and getServerSideProp is greatly desirable, since getInitialProps will be deprecated and most likely deleted from next. js .

What is difference between getInitialProps and getServerSideProps?

Is there a difference between getInitialProps and getServerSideProps ? The main difference between the legacy getInitialProps and the newer getServerSideProps is how the function is used during transitions, when users click on a Link to visit different parts of your site.


1 Answers

Cache-Control headers are overridden in development, so that pages do not get cached by the browser.

It will work in production (next build && next start).

like image 105
Bertrand Marron Avatar answered Oct 11 '22 17:10

Bertrand Marron