Forcing internet and phone operators to carry out the "general and indiscriminate transmission or retention of traffic data and location data" is against EU law, the court explained in its ruling.
"However, in situations where a member state is facing a serious threat to national security that proves to be genuine and present or foreseeable, that member state may derogate from the obligation to ensure the confidentiality of data relating to electronic communications," it continues.
Even in these emergency scenarios, there are rules that must be adhered to.
"Such an interference with fundamental rights must be accompanied by effective safeguards and be reviewed by a court or by an independent administrative authority," the court said.
The ruling, which has been eagerly anticipated by civil rights campaigners, is in response to several cases brought about by Privacy International and La Quadrature du Net.The campaign groups argued that surveillance practices in the U.K., France and Belgium go too far and violate fundamental human rights. The groups specifically took issue with the U.K.'s Investigatory Powers Act, a 2015 French decree related to specialized intelligence services, and a Belgian law on collection and retention of communications data that was introduced in 2016.
"Today's judgment reinforces the rule of law in the EU," said Caroline Wilson Palow, legal director of Privacy International, in a statement. "In these turbulent times, it serves as a reminder that no government should be above the law. Democratic societies must place limits and controls on the surveillance powers of our police and intelligence agencies."Palow added: "While the Police and intelligence agencies play a very important role in keeping us safe, they must do so in line with certain safeguards to prevent abuses of their very considerable power. They should focus on providing us with effective, targeted surveillance systems that protect both our security and our fundamental rights."