Spider is a type of arthropods. The word "arthropod" comes from Greek, meaning jointed feet. Arthropod body is segmented. In certain segments, there are paired appendages. It turned out that during the development, the arthropod embryo is also segmented. Each segment is called a somite. It turned out that a group of genes called homeobox genes regulate how each somite develops and only certain types of somite will eventually grow a pair of legs.
All animals except sponges and some jelly fishes have specific types of homeobox genes called Hox genes. They are responsible for how the animal body develop.
Hox genes produces types of proteins called transcription factors. Those transcription factors recognizes certain regions on the DNA called the homeobox and changes how the gene the homeobox is in are expressed.
Although there are very few experiment on the development of spiders, scientists have created fruit fly mutants with two pairs of legs and four pairs of legs.
In summary, a unique combination of Hox genes regulated spider's development and make them four pairs of legs.