CORS erro with nextjs fetch in Go API

I have a Nextjs application for my front-end and an API with Go, specifically on the requires authorization endpoint, every time, return this error.

controller:

func RecoverUser(w http.ResponseWriter, r *http.Request) {
	userIDInToken, erro := authetication.ExtractUserID(r)
	if erro != nil {
		responses.Erro(w, http.StatusUnauthorized, erro)
		return
	}

	var user models.User
	record := database.Instance.First(&user, "id = ?", userIDInToken)
	if record.Error != nil {
		responses.Erro(w, http.StatusInternalServerError, record.Error)
		return
	}

	responses.JSON(w, http.StatusOK, user)
}

middlewares:

func Authenticate(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := authetication.ValidateToken(r); err != nil {
			responses.Erro(w, http.StatusUnauthorized, err)
			return
		}
		next(w, r)
	}
}

func EnableCorsDevelopment(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// Permitir solicitações de qualquer origem
		w.Header().Set("Access-Control-Allow-Origin", config.FrontEndUrl)
		// Permitir os métodos HTTP especificados
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		// Permitir os cabeçalhos especificados
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		w.Header().Set("Acess-Control-Allow-Credentials", "true")

		next(w, r)
	}
}

fetch nexjs:

useEffect(() => {
        if (Cookies.get('token')) {
            const token = Cookies.get('token')
            const fetchData = async () => {
                const response = await fetch(BASE_URL_API + '/recuperar/usuario', {
                method: 'GET',
                headers: {
                    'Content-type': 'application/json',
                    'Authorization': `Bearer ${token}` 
                    },
                })
                if (!response.ok) {
                    console.log('ERRO')
                } else {
                    const result = await response.json()
                    setUser(result.user)
                }
            }

            fetchData()
        }
    }, [])

Can you show the code where you “use” the middlewares?
Can you see the response header?

Hi Massimo! I got fix this problem added these cors options in my router and preflight request of nextjs is accepted

func main() {
	config.LoadEnvironment()

	database.Conect()
	database.Migrate()

	r := router.Generate()

	cors := cors.New(cors.Options{
        AllowedOrigins:   []string{config.FrontEndUrl},
        AllowedHeaders:   []string{"*"},
        AllowedMethods:   []string{"GET", "PATCH", "POST", "PUT", "OPTIONS", "DELETE"},
        AllowCredentials: true,
    })

	handler := cors.Handler(r)

	log.Printf("Escutando na porta %d\n", config.Port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.Port), handler))
}
1 Like