LONDON—European governments can’t require internet companies to retain data indiscriminately, the European Union’s top court said Wednesday in a ruling that could complicate their efforts to expand surveillance powers.

The decision by the Court of Justice of the European Union is the latest blow to law enforcement authorities in Europe who say they need access to communications data to fight terrorism and other crime. The ruling is a boost for privacy advocates and paves the way for further legal challenges against surveillance...