There are a lot of hazards in outer space, such as temperature, space debris, and radiation. Spacecraft designers keep these factors in mind when creating something that needs to last an extended period in the harsh environment.
Regarding temperature, some spacecraft utilize onboard temperature control systems. For example, the Rosetta spacecraft has louvers that can open or close depending on the temperature - they open in the warmth to dissipate heat and close in the cold to trap heat. The James Webb Space Telescope, on the other hand, will use a unique cooling system that keeps some components colder than the space around it.
Another problem is space debris, and it's almost everywhere. Space debris travels several times faster than a bullet, but much of it is too small to see. Engineers typically avoid known space debris areas whenever possible, but they can also use folding tactics that reduce surface area when space debris will be unavoidable.
Radiation can fry the sensitive computer systems inside of a spacecraft, so engineers use electronic redundancy and shielding to prevent corrupted data. With electronic redundancy, several of the same electronics process the same information simultaneously to ensure that NASA doesn't receive corrupted data. Shielding is less common, as it adds weight and increases the cost of the launch.
Because space missions aren't cheap, NASA spends a lot of their budget on research and development to ensure the longevity of their spacecraft. The reward can be priceless, especially if that spacecraft holds up to the test of time.