A shunt active power filter (APF) is a well-mature technology for the compensation of nonlinear and/or reactive loads. Normally, the shunt APF is controlled such that it eliminates the load current harmonics and supplies load reactive power to achieve harmonic-free source currents at unity power factor. However, these control objectives cannot be achieved simultaneously when the supply voltages are distorted and unbalanced (nonideal). Hence, under such situation, the shunt APF should be controlled optimally to achieve a maximum possible power factor without violating the current harmonic constraints recommended by IEEE Std. 519. This paper presents an optimal algorithm to control a three-phase four-wire shunt APF under nonideal supply conditions. The optimization problem aiming at maximizing the power factor subject to current harmonic constraints as per IEEE Std. 519 has been formulated and solved mathematically using the Lagrangian formulation. The proposed algorithm avoids the use of complex iterative optimization techniques and thus is simple to implement and has fast dynamic response. The effectiveness of the proposed method is evaluated through a detailed experimental investigation using a digital signal processor controlled shunt APF prototype developed in the laboratory.