We study the formation of networks in environments where agents derive benefits from other agents directly linked to them but suffer losses through contagion when any agent on a path connected to them is hit by a shock. We first consider networks with undirected links (e.g. epidemics, underground resistance organizations, trade networks) where we find that stable networks are comprised of completely connected disjoint subnetworks. Then, we consider networks with directed links and we find that the completely connected network is stable, although, its exact structure, and thus contagion implications, is sensitive to parameter values for costs and benefits. Lastly, we introduce aggregate externalities (e.g. fire sales for the case of financial networks) and we find that stable networks can be asymmetric, connected but not completely connected, thus capturing the main features of inter-industry and financial networks.