Next.js Discord

Discord Forum

Getting undefine value for a cookie I set during middleware in a SSR'd page.

Unanswered
Kuchi posted this in #help-forum
Open in Discord
KuchiOP
Hey guys getting an undefined value from a cookie that gets set in my middleware when I try to access it during getServerSideProps. Trying to figure out why its undefined when its value returns from the geolocation-api I made.

export const getServerSideProps = withSessionSsr(
  async function getServerSideProps({ req }) {
    const location = req.session.location;
    console.log("location in ssr", location)

    return {
      props: {
        location: req?.session?.location,
      },
    };
  },
);



//_middleware.js
import { NextResponse } from "next/server";
import { getIronSession } from "iron-session/edge";
import { sessionOptions } from "./lib/session";

export const middleware = async (req) => {
  if (
    req.nextUrl.pathname.startsWith("/_next") ||
    req.nextUrl.pathname.includes("/api/")
  ) {
    return;
  }
  //uses browser head to detect local on initial visit
  const res = NextResponse.next();
  const urlAlberta = req.nextUrl.clone();
  const path = req.nextUrl.pathname;
  //get current session if it exists
  const session = await getIronSession(req, res, sessionOptions);
  //grab current session + display current session data
  const { location } = session;

  //NO SESSIONS
  //get user IP and set the browser session for user location
  if (!session.location) {
    //   fetch user IP + local data and set it in a session cookie
    const url =
      process.env.NODE_ENV === "production"
        ? process.env.PROD_URL + `api/geolocation-api`
        : process.env.DEV_URL + `api/geolocation-api`;

    const res_location = await fetch(url);
    const locationData = await res_location.json().then();
    session.location = locationData;
    await session.save();

  }
  return res;
};



//  /api/geolocation-api.js
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "../../lib/session";

export default withIronSessionApiRoute(async (req, res) => {
  const apiKey = process.env.GEOLOCATION_API_KEY;


  //get User IP Address
  let ip = "";
  if (req.headers["x-forwarded-for"]) {
    // When not running on localhost
    ip = req.headers["x-forwarded-for"];
  } else if (req.socket.remoteAddress && req.socket.remoteAddress !== "::1") {
    // When running on localhost with IP other than '::1' 
    //indian ip : 103.10.168.0
    //CA ip :     142.31.216.15
    //alberta IP : 96.52.251.111
    ip = "103.10.168.0";
  }

  const url = `https://geo.ipify.org/api/v2/country,city?apiKey=${apiKey}&ipAddress=${ip}`;

  try {
    const response = await fetch(url);
    if (response.ok) {
      const data = await response.json();

      const location = {
        country: data.location.country,
        region: data.location.region,
      };
      console.log("fetched location data", location)
  
      res.status(200).json({ location });
    } else {
      throw new Error("Failed to fetch geolocation");
    }
  } catch (error) {
    console.error("Error fetching geolocation:", error);
    res.status(500).json({ error: "Failed to fetch geolocation" });
  }
}, sessionOptions);
//this returns data with the user's location

0 Replies