The US supreme court on Tuesday endorsed US government authority to detain immigrants awaiting deportation at any time – potentially even years – after they have completed prison terms for criminal convictions, handing Donald Trump a victory as he pursues hardline immigration policies.

The court ruled 5-4, with its conservative justices in the majority and its liberal justices dissenting, that federal authorities could pick up such immigrants and place them into indefinite detention at any time, not just immediately after they finish their prison sentences.

The ruling, authored by the conservative justice Samuel Alito, leaves open the possibility of individual immigrants challenging the federal law involved in the case on constitutional grounds if they are detained long after they have completed their sentences.

In dissent, the liberal justice Stephen Breyer questioned whether the US Congress when it wrote the law “meant to allow the government to apprehend persons years after their release from prison and hold them indefinitely without a bail hearing”.

The Trump administration had appealed against a lower court ruling in the case that favored immigrants, a decision it said would undermine the government’s ability to deport immigrants who have committed crimes. Trump has backed limits on legal and illegal immigrants since taking office in January 2017.

The plaintiffs included two legal US residents involved in separate lawsuits filed in 2013, a Cambodian immigrant named Mony Preap convicted of marijuana possession and a Palestinian immigrant named Bassam Yusuf Khoury convicted of attempting to manufacture a controlled substance.

Under federal immigration law, immigrants convicted of certain offenses are subject to mandatory detention during their deportation process. They can be held indefinitely without a bond hearing after completing their sentences.