Morocco was the first nation, in 1777, to recognize the fledgling United States as an independent nation. In the beginning of the American Revolution, American merchant ships were subject to attack by the Barbary Pirates while sailing the Atlantic Ocean. At this time, American envoys tried to obtain protection from European powers, but to no avail. On 20 December 1777, Morocco's Sultan Mohammed III declared that the American merchant ships would be under the protection of the sultanate and could thus enjoy safe passage.
https://en.wikipedia.org/wiki/Morocco#Alaouite_Dynasty_1666.E2.80.931912
This article says that Morooco was "one of the first", though.
Morocco and the United States have a long history of friendly relations. During the American Revolution when the 13 Colonies were fighting against Great Britain, Morocco was one of the first states to acknowledge publicly the independence of the young Republic. In nearly identical declarations dated December 20, 1777, and February 20, 1778, distributed to all foreign consuls in Morocco, Sultan Sidi Muhammad stated he had given American ships and those of nine European states, with which it had no treaties, the right-of-entry into Moroccan ports.
https://ma.usembassy.gov/our-relationship/policy-history/io
Here is another view -- Quote (removing typos) -- November 16, 1776, The Dutch island of St. Eustatius gives first foreign salute to the American flag. But Holland will not formally recognize the independence of the United States, until 1778, the second country to do so.
*** March 13, 1778 - France recognizes American independence and concludes an alliance with the thirteen *states*. So that would be the official recognition by a foreign government.
[From answerbag.com 2007 article, no longer online]
I think I will trust this one, though:
Morocco was the first country to recognize the independence of the United States of America from the Kingdom of Great Britain in 1777. The two countries signed the Moroccan-American Treaty of Friendship ten years later. Friesland, one of the seven United Provinces of the Dutch Republic, was the next to recognize American independence (on February 26, 1782, followed by the Staten-Generaal of the Dutch Republic on April 19, 1782). John Adams became the first US Ambassador in The Hague. The American Revolution was the first wave of the Atlantic Revolutions that took hold in the French Revolution, the Haitian Revolution, and the Latin American wars of liberation. Aftershocks reached Ireland in the 1798 rising, in the Polish-Lithuanian Commonwealth, and in the Netherlands.
https://en.wikipedia.org/wiki/American_revolution