The Taliban told the BBC a suicide bomber had detonated explosives outside the building before dawn on Friday.
Other fighters then opened fire on the consulate. Several Afghan police are reported to have been killed and injured in the gun battle.
It is the latest in a series of attacks ahead of the withdrawal of foreign combat troops from Afghanistan in 2014.
An Afghan army spokesman told the BBC that the initial explosion had damaged outer defences of the US consulate, allowing the attackers to breach the perimeter and shoot at the consulate buildings. The bomb had been placed in a car.
The gunfire continued for some time, reporters at the scene said.
The Nato-led International Security Assistance Force (Isaf) tweeted at 0400 GMT that the consulate was secure "with all enemy forces being killed".
Isaf and Afghan National Security Forces were at the scene, it added.
The BBC's David Loyn in Kabul says the attack - carried out in the shadow of the anniversary of the 9/11 attacks on the US - is a demonstration of the ability of insurgents still to disrupt Afghanistan 12 years on.
Two Afghan police and one locally hired guard were killed, our correspondent adds.
"All consulate personnel are safe and accounted for," a US Embassy spokesman told AP news agency.
Herat, close to the Iranian border, has been relatively peaceful in recent years.
Earlier this month Taliban targeted the Torkham US base in eastern Afghanistan, sparking a lengthy gun battle in which three insurgents were killed.
Other fighters then opened fire on the consulate. Several Afghan police are reported to have been killed and injured in the gun battle.
It is the latest in a series of attacks ahead of the withdrawal of foreign combat troops from Afghanistan in 2014.
An Afghan army spokesman told the BBC that the initial explosion had damaged outer defences of the US consulate, allowing the attackers to breach the perimeter and shoot at the consulate buildings. The bomb had been placed in a car.
The gunfire continued for some time, reporters at the scene said.
The Nato-led International Security Assistance Force (Isaf) tweeted at 0400 GMT that the consulate was secure "with all enemy forces being killed".
Isaf and Afghan National Security Forces were at the scene, it added.
The BBC's David Loyn in Kabul says the attack - carried out in the shadow of the anniversary of the 9/11 attacks on the US - is a demonstration of the ability of insurgents still to disrupt Afghanistan 12 years on.
Two Afghan police and one locally hired guard were killed, our correspondent adds.
"All consulate personnel are safe and accounted for," a US Embassy spokesman told AP news agency.
Herat, close to the Iranian border, has been relatively peaceful in recent years.
Earlier this month Taliban targeted the Torkham US base in eastern Afghanistan, sparking a lengthy gun battle in which three insurgents were killed.
Comment