Abstract. We devise an efficient algorithm for the finite element construction of discrete harmonic fields and the numerical solution of 3D magnetostatic problems. In particular, we construct a finite element basis of the first de Rham cohomology group of the computational domain. The proposed method works for general topological configurations and does not need the determination of "cutting" surfaces.