Extract TLD from hostname string

I have the following hostnames and they TLDs.

  • dev.sitename.com (.com)
  • sitename.com (.com)
  • sitename.co.uk (.co.uk)
  • dev.sitename.co.uk (.co.uk)
  • staging.sitename.k34.com (.com)
  • local.sitename.com:3000 (.com)(Is used on local webserver virtual host for testing)
  • local.sitename.co.uk:3000 (.co.uk)(Is used on local webserver virtual host for testing)

These hostnames are fetched from NextJS getServerSideProps via

export const getServerSideProps = async (ctx) => {
  const hostname = ctx.req.headers.host;
};

I can’t seem to use a method than can handle subdomains and second level domains like .co.uk and potentially handle port numbers?

What I initially had was

const getTld = (hostname: string) => {
  return hostname.split(/./).slice(-1).join('.');
}

but for

getTld("sitename.co.uk")

it returns uk, not co.uk

for

getTld("local.sitename.co.uk:3000")

it returns uk:3000, not co.uk

Any help would be greatly appreciated!