The Hồng Bàng dynasty of the Hùng kings first established in 2879 BC is considered the first Vietnamese state in the History of Vietnam (then known as Xích Quỷ and later Văn Lang). In 257 BC, the last Hùng king was defeated by Thục Phán. He consolidated the Lạc Việt and Âu Việt tribes to form the Âu Lạc, proclaiming himself An Dương Vương. In 179 BC, a Chinese general named Zhao Tuo defeated An Dương Vương and consolidated Âu Lạc into Nanyue. However, Nanyue was itself incorporated into the empire of the Chinese Han dynasty in 111 BC after the Han–Nanyue War. For the next thousand years, what is now northern Vietnam remained mostly under Chinese rule. Early independence movements, such as those of the Trưng Sisters and Lady Triệu were temporarily successful, though the region gained a longer period of independence as Vạn Xuân under the Anterior Lý dynasty between AD 544 and 602. By the early 10th century, Vietnam had gained autonomy, but not sovereignty, under the Khúc family.
In AD 938, the Vietnamese lord Ngô Quyền defeated the forces of the Chinese Southern Han state at Bạch Đằng River and achieved full independence for Vietnam after a millennium of Chinese domination. Renamed Đại Việt (Great Viet), Vietnamese society enjoyed a golden era under the Lý and Trần dynasties. During the rule of the Trần Dynasty, Đại Việt repelled three Mongol invasions. Meanwhile, the Mahāyāna branch of Buddhism flourished and became the state religion. Following the 1406–7 Ming–Hồ War, which overthrew the Hồ dynasty, Vietnamese independence was interrupted briefly by the Chinese Ming dynasty, but was restored by Lê Lợi, the founder of the Lê dynasty. The Vietnamese dynasties reached their zenith in the Lê dynasty of the 15th century, especially during the reign of Emperor Lê Thánh Tông (1460–1497). Between the 11th and 18th centuries, Vietnam expanded southward in a process known as Nam tiến (“Southward expansion”), eventually conquering the kingdom of Champa and part of the Khmer Kingdom.
From the 16th century onward, civil strife and frequent political infighting engulfed much of Vietnam. First, the Chinese-supported Mạc dynasty challenged the Lê dynasty’s power. After the Mạc dynasty was defeated, the Lê dynasty was nominally reinstalled. Actual power, however, was divided between the northern Trịnh lords and the southern Nguyễn lords, who engaged in a civil war for more than four decades before a truce was called in the 1670s. During this period, the Nguyễn expanded southern Vietnam into the Mekong Delta, annexing the Central Highlands and the Khmer lands in the Mekong Delta. The division of the country ended a century later when the Tây Sơn brothers established a new dynasty. However, their rule did not last long, and they were defeated by the remnants of the Nguyễn lords, led by Nguyễn Ánh, aided by the French. Nguyễn Ánh unified Vietnam, and established the Nguyễn dynasty, ruling under the name Gia Long.