Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
How to redirect and send data in getInitialProps in Next.js

On index.js page I am fetching data that I would like all my pages has access to, but also depending on the data I receive, I want to redirect. How to redirect and pass data at the same time?

My code on _app.js

import "styles/globals.css";
import React from "react";
import axios from "axios";
import getServiceAddress from "service/get-service-address";
import Router from "next/router";
export const MyContext= React.createContext({});

function MyApp({ Component, pageProps, data, redirect }) {
  return (
      <MyContext.Provider value={data}>
        <Component {...pageProps} />
      </MyContext.Provider>
  );
}

MyApp.getInitialProps = async (context) => {
  if (context.ctx.pathname !== "/") { //if not index then do nothing
    return {};
  }

  const id= context.ctx.query.id;
  try {
    const url = `http://somepage.com/${id}`;

    const res = await axios.get(url);
    const data = res.data;

    if (data.hasSomeValue) {
       /// I want to redirect and send the data
      return {
        data: data,
        redirect: "/success",
      };
    }

    return { data };
  } catch (e) {
    return {
      redirect: "/error",
    };
  }
};

export default MyApp;

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!