The Islamic State group on Saturday claimed responsibility for a massacre in a Tunisian seaside resort that killed nearly 40 people in the worst attack in the country's recent history.

The militants said the gunman, who they identified as Abu Yahya al-Qayrawani, was a "soldier of the caliphate" who had targeted enemies of IS and "dens... of vice" in Port el Kantaoui.

READ ALSO: 27 dead in Tunisia tourist resort attack


Most of those killed were "subjects of states that make up the crusader alliance fighting the state of the caliphate", the group said in a statement released on Twitter.

The attack targeted "dens (of...) fornication, vice and apostasy in the city of Sousse" and was carried out "despite (security) measures strengthened around these dens on Kantaoui beach," it added.

The carnage at the popular Mediterranean resort, 140 kilometres (85 miles) south of the capital, left 39 dead and dozens more injured in the second attack against tourists this year.

An attack in March on the Bardo Museum in Tunis -- also claimed by IS -- killed 22 people and dealt a large blow to the country's vital tourism industry.

Tunisia has faced a rise in Islamist violence since a 2011 uprising that saw the overthrow of its government and sparked the beginning of the Arab Spring across the Middle East.