Next.js Discord

Discord Forum

How to get the current URL from getServerSideProps function in Next.js 13.4 (using pages router)?

Unanswered
American Crocodile posted this in #help-forum
Open in Discord
Avatar
American CrocodileOP
I want to get the subdomain from the current URL in the server so I can perform some data fetching using this subdomain.

So in the /pages/index.tsx I did this

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
    const queryClient = new QueryClient();
    const sessionCookie: CookieValueTypes = getCookie(Cookies.SESSION, { req, res });
    const domainCookie: CookieValueTypes = getCookie(Cookies.DOMAIN_INFO, { req, res });

    let domain: Domain | null = null;

    if (!domainCookie) {
        if (!req || !req.headers || !req.headers.host) throw new Error("Can't get host from request headers");

        const subdomain = req.headers.host.split(':')[0];

        try {
            domain = await queryClient.fetchQuery([Endpoints.SITE, { subdomain }], fetchData);
        } catch (error: any) {
            console.error('Unable to fetch subdomain info');
        }

        setCookie(Cookies.DOMAIN_INFO, JSON.stringify(domain), { req, res });
    } else {
        domain = JSON.parse(domainCookie as string);
    }

    // The rest of the code
};


The problem here is when I go to http://application:3005 the subdomain should return the word application but instead it returns this 127.0.0.1.

NOTE: I have already configured the correct mapping in the hosts file on my machine, I'm running Windows 11 and that's how my hosts file look like

127.0.0.1 localhost
127.0.0.1 application
::1 localhost

0 Replies