PurposeThis paper aims to achieve phosphating via optimal features of Mg metal as a suitable base coating, which is considered for other properties such as barrier properties against the passage of several factors.Design/methodology/approachIn this research, in the phosphate bath, immersion time, temperature and the content of sodium nitrite as an accelerator were changed.FindingsAs a result, increasing the immersion time of AZ31 Mg alloy samples in the phosphating bath as well as increasing the ratio of sodium dodecyl sulfate (SDS) concentration to sodium nitrite concentration in the phosphating bath formulation increase the mass of phosphating formed per unit area of the Mg alloy. The results of the scanning electron microscope test showed phosphating is not completely formed in short immersion times, which is a thin and uneven layer.Research limitations/implicationsMg and its alloys are sensitive to galvanic corrosion, which would lead to generating several holes in the metal. As such, it causes a decrease in mechanical stability as well as an unfavorable appearance.Practical implicationsMg is used in several industries such as automobile and computer parts, mobile phones, astronaut compounds, sports goods and home appliances.Social implicationsNevertheless, Mg has high chemical reactivity, so an oxide-hydroxide layer is formed on its surface, which has a harmful effect on the adhesion and uniformity of the coating applied on Mg.Originality/valueBy increasing the ratio of SDS concentration to sodium nitrite concentration in the phosphating bath, the corrosion resistance of the phosphating increases.