An American surfer was attacked by a crocodile at a popular tourist beach in Costa Rica (Representational image) Getty Images

A US surfer has survived a crocodile attack in Costa Rica after his friend fought off the reptile and saved him from becoming its prey. The injured man later underwent surgery.

According to Pat McNulty, a consultant and a trained lifeguard in the northwestern town of Tamarindo, who was present during the incident, the man was crossing a river near a popular tourist beach in the country with the friend when the crocodile attacked.

"He was bitten several times in the leg as well as the head. They were able to get him free, swim him to safety and then trained lifeguards responded... and we administered first aid and called an ambulance," McNulty told Associated Press.

"His friend saved his life...and then we the lifeguards helped keep him alive. It was a very traumatic scene, and all individuals attending him did a tremendous job," he added.

However, he declined to provide the name of the man who was attacked, only saying he was a surfer from Colorado, who had came to the beach with his family.

"We live in a country where there's large crocodiles, and people take for granted that when you go into a river that you're safe," McNulty said.

"But the fact of the matter is that you need to be aware of your environment. ... We're in their world," the lifeguard added.