How to use getServerSideProps for every pages in next.js?

As of now, there isn’t a built-in way to do it, so I’ve resorted to doing the following.

First, I created a file that holds the getServerSideProps function I want to run on every page:

// lib/serverProps.js
export default async function getServerSideProps(ctx) {
  // do something
  return {
    // data
  };
}

Then in every page (yes, every, I can’t find a workaround; it might even be helpful if you don’t need the code to execute on server pages), do:

import getServerSideProps from "../lib/serverProps";

// other stuff...

export { getServerSideProps };

or

// other stuff...

export { default as getServerSideProps } from "../lib/serverProps";

If you want to add other code to run inside getServerSideProps for a specific page, you could do something along the lines…

import serverProps from "../lib/serverProps";

// other stuff...

export async function getServerSideProps(ctx) {
  // do custom page stuff...
  return {
    ...await serverProps(ctx),
    ...{
      // pretend this is what you put inside
      // the return block regularly, e.g.
      props: { junk: 347 }
    }
  };
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)