This paper presents the detailed design, analysis, and application of the controller for a shunt active power filter based on a pulsewidth modulation dc-to-ac voltage source converter. The controller is mainly tailored to compensate harmonic currents of nonlinear loads connected to the mains. However, it can also achieve reactive-power compensation and mains-current balancing when required. The controller has a two-layer structure. The outer layer generates the current references for the inner layer. The former uses a plug-in discrete-time repetitive algorithm for current-harmonic compensation, a proportional–integral algorithm to maintain the dc-capacitor voltage in spite of unmodeled losses and a reactive-power-reference generator. The inner layer uses state-feedback with integral action for current control. The repetitive controller is justified to improve the tracking of the periodic current references required by the active filters. The stability of the resulting closed-loop system is studied and some indication of the system robustness is given. The proposed controller has been tested in a prototype with balanced and unbalanced nonlinear loads. A discrete-time model of the filter has been used from the beginning. The microcomputer delay when calculating the controller output and the delay due to the anti-aliasing filters have been included in the inner system state-variable model.