Any ships that wanted to do business in the Mediterranean were at risk. Many European countries did the easy thing and paid the protection money to the pirates to avoid being raided, which, of course, helped fund the pirates' operations against anyone who wasn't paying.
The U.S. didn't have the military resources to protect its ships, so it paid the protection money too. This really bothered Thomas Jefferson.
Before he was president, when he was an ambassador to France, Jefferson had a chance to meet with an ambassador from Tripoli (one of the Barbary Coast countries), and he asked why Tripoli attacked U.S. ships. After all, the U.S. had never done anything against Tripoli. The ambassador explained that it was written in the Koran that faithful Muslims must make war on non-believers and it was a religious duty for them to plunder and enslave the non-believers.
Thomas Jefferson was shocked by this, but skeptical. So he bought himself a Koran and read it. He discovered that the Tripoli ambassador had told him the truth.
When he became president in 1801, he knew what he needed to do: He expanded the puny United States Navy so it could protect American ships from piracy in the Mediterranean, and then he sent Marines to the shores of Tripoli and soundly defeated them. America never again paid the pirates protection money.
This was the first foreign war fought by the United States. America's victory was the beginning of the end of the Barbary Coast Pirates.