Encountering a challenge within a Next.js application (for a coding challenge).
Requested flow to achieve:
- Check for geolocation cookie in Next middleware. If not present, fetch data and store in cookie.
- In
getServerSideProps
, utilize the cookie (if available) to pass geolocation data as prop to component.
Current implementation sets cookie in middleware but getServerSideProps cannot access it on initial render. Cookie is accessible on page refresh/subsequent calls.
Insight from ChatGPT:
Upon user's first visit, middleware correctly identifies absence of cookie, retrieves geolocation data and sets cookie in response. Issue arises as getServerSideProps runs after middleware but before client receives cookie for subsequent requests.
Snippet of code:
Middleware:
export async function middleware(req: NextRequest) {
// Code snippet here
}
ServerSideProps of index page:
export const getServerSideProps = (async ({ req }) => {
// Code snippet here
}) satisfies GetServerSideProps<RootPageProps>
Constraint: Need an efficient way to ensure geolocation data availability without making duplicated calls during initial render for millions of users requesting the page.
Any potential solutions?