Next.js Discord

Discord Forum

Using Iron Session to store user location data by IP, how do I get this data into my component?

Unanswered
Kuchi posted this in #help-forum
Open in Discord
KuchiOP
Currently call the API in _middleware.js and set it in the iron session cookie.

import { NextResponse } from "next/server";
import { getIronSession } from "iron-session/edge";
import { sessionOptions } from "./lib/session";
export const middleware = async (req) => {
  const res = NextResponse.next();
  //get current session if it exists
  const session = await getIronSession(req, res, sessionOptions);
  //grab current session + display current session data
  const { location } = session;
  //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;
};

export const config = { matcher: "/((?!.*\\.).*)" };

4 Replies

you can add a custome header to transfer it to server components.
besides that, you can leverage Vercel Edge mechanisim to grab IP, geo etc.

https://vercel.com/docs/concepts/functions/edge-functions/vercel-edge-package#ipaddress
im not sure about iron-cookie, but cookie can be tailored by cURL or whatever.
ah, it's encrypted like JWE. cool.