Installing electrical box in 2x4
A box can penetrate any material, not just 1/2&quot; drywall.
For non-flammable surfaces you can have the box set back up to 1/4&quot;. Ultimately though you want to be flush with the surface.
For flammable surfaces you must be flush with the finished surface.
This is borrowed from a post by @tester101:

ARTICLE 314
Outlet, Device, Pull, and Junction Boxes;
Conduit Bodies; Fittings; and Handhole Enclosures
314.20 In Wall or Ceiling. In walls or ceilings with a surface of concrete, tile, gypsum, plaster, or other noncombustible material,
boxes employing a ﬂush-type cover or faceplate shall be installed so
that the front edge of the box, plaster ring, extension ring, or
listed extender will not be set back of the ﬁnished surface more than
6 mm (1⁄4 in.). In walls and ceilings constructed of wood or other
combustible surface material, boxes, plaster rings, extension rings,
or listed extenders shall be ﬂush with the ﬁnished surface or project
therefrom.

This might also be relevant.

406.4 Receptacle Mounting. Receptacles shall be mounted in boxes or assemblies designed for the purpose, and such boxes or assemblies
shall be securely fastened in place unless otherwise permitted
elsewhere in this Code.
(A) Boxes That Are Set Back. Receptacles mounted in boxes that are set back from the finished surface as permitted in 314.20 shall be
installed such that the mounting yoke or strap of the receptacle is
held rigidly at the finished surface.