Questions & Answers

How to Fetch Dynamic URL Path within Next.js File

I'm trying to find exactly what page the user is on. I'm creating a search bar such that when the user hits enter, they are led to another page with their query. For this, I am using a dynamic path. When the user types "abc" for example and searches it, they get led to a page "localhost:3000/search/abc".

I do this through a dynamic path, where I have a Next.js page rendered called search and a folder inside it called [searchText] which has an index.tsx file. I want to know what searchText is so I can query it against my database. However, I can't use window.location.href even inside a useEffect (useEffect seems to not be working on any of my pages) and using the React-Dom Router just gives me:

ServerRouter { route: '/search/[searchText]', pathname: '/search/[searchText]', query: {}, asPath: '/search/[searchText]', isFallback: false, basePath: '', locale: undefined, locales: undefined, defaultLocale: undefined, isReady: false,
domainLocales: undefined, isPreview: false, isLocaleDomain: false }

This prevents me from using asPath and actually getting meaningful information. Does anyone know of any workarounds to this problem?

I tried the window.location.href which didn't work because window was not defined. useEffect is not working at all even when I import it (maybe this has something to do with how my React/TypeScript/Next app is set up) and the router when initialized in /search/[searchText]/index.tsx is unable to return meaningful information as there is nothing of meaning in asPath and query.

Answers(1) :

Turns out this was very stupid. Didn't realize console.log() was logging in the console online, not VSCode's console. Most of the time console.log() is just logging in VSCode so that was surprising. Everything is working now. Ended up not doing window.location.href because that was returning nothing and just using location.href which is working properly.