How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Gin · Go

Fix RuntimePanic: runtime error: invalid memory address or nil pointer dereference in middleware in Gin

This panic occurs when a Gin middleware dereferences a nil pointer, typically by accessing a value from the context that was never set or by calling a method on an uninitialized dependency. Fix it by adding nil checks in your middleware, ensuring all dependencies are injected before the server starts, and using Gin's built-in recovery middleware.

Reading the Stack Trace

2024/03/15 14:30:12 [Recovery] 2024/03/15 - 14:30:12 panic recovered: runtime error: invalid memory address or nil pointer dereference goroutine 21 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e github.com/gin-gonic/gin.(*Context).Next.func1() /go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:176 +0x84 runtime.gopanic({0x102840ea0, 0x1040b8900}) /usr/local/go/src/runtime/panic.go:770 +0x124 main.AuthMiddleware(0x14000226000) /app/middleware/auth.go:18 +0xd8 github.com/gin-gonic/gin.(*Context).Next(0x14000226000) /go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 +0x74 github.com/gin-gonic/gin.RecoveryWithWriter.func1(0x14000226000) /go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/recovery.go:102 +0x318 github.com/gin-gonic/gin.(*Context).Next(0x14000226000) /go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 +0x74

Here's what each line means:

Common Causes

1. Uninitialized service dependency

The middleware uses a service that was never initialized, so calling a method on it dereferences nil.

var userService *UserService // nil — never assigned

func AuthMiddleware(c *gin.Context) {
	token := c.GetHeader("Authorization")
	user, _ := userService.ValidateToken(token) // panic: nil pointer
	c.Set("user", user)
	c.Next()
}

2. Missing context value from upstream middleware

The middleware reads a value from the Gin context that a previous middleware was supposed to set but didn't.

func RoleMiddleware(c *gin.Context) {
	user := c.MustGet("user").(*User) // panics if "user" key not set
	if user.Role != "admin" {
		c.AbortWithStatus(403)
		return
	}
	c.Next()
}

3. Nil return from header parsing

Parsing the Authorization header returns nil and the code dereferences it without checking.

func AuthMiddleware(c *gin.Context) {
	claims := parseJWT(c.GetHeader("Authorization"))
	c.Set("userID", claims.UserID) // panic if claims is nil
	c.Next()
}

The Fix

Replace the package-level nil variable with a constructor function that takes the dependency as a parameter and validates it at startup. Check the token and error values before using them to prevent nil pointer dereferences at runtime.

Before (broken)
var userService *UserService

func AuthMiddleware(c *gin.Context) {
	token := c.GetHeader("Authorization")
	user, _ := userService.ValidateToken(token)
	c.Set("user", user)
	c.Next()
}
After (fixed)
func NewAuthMiddleware(svc *UserService) gin.HandlerFunc {
	if svc == nil {
		panic("NewAuthMiddleware: UserService must not be nil")
	}
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
			return
		}
		user, err := svc.ValidateToken(token)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
			return
		}
		c.Set("user", user)
		c.Next()
	}
}

Testing the Fix

package middleware_test

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
)

func TestAuthMiddleware_MissingHeader(t *testing.T) {
	gin.SetMode(gin.TestMode)
	r := gin.New()
	svc := &UserService{}
	r.Use(NewAuthMiddleware(svc))
	r.GET("/test", func(c *gin.Context) { c.Status(200) })

	req := httptest.NewRequest(http.MethodGet, "/test", nil)
	w := httptest.NewRecorder()
	r.ServeHTTP(w, req)

	assert.Equal(t, http.StatusUnauthorized, w.Code)
}

func TestAuthMiddleware_NilServicePanicsAtInit(t *testing.T) {
	assert.Panics(t, func() {
		NewAuthMiddleware(nil)
	})
}

Run your tests:

go test ./middleware/... -v

Pushing Through CI/CD

git checkout -b fix/gin-middleware-panic,git add middleware/auth.go middleware/auth_test.go,git commit -m "fix: inject UserService into auth middleware to prevent nil panic",git push origin fix/gin-middleware-panic

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: '1.22'
      - run: go mod download
      - run: go vet ./...
      - run: go test ./... -race -coverprofile=coverage.out
      - run: go build ./...

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

go get github.com/bugstack/sdk

Step 2: Initialize

import "github.com/bugstack/sdk"

func init() {
  bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run go test ./... locally to confirm the fix passes.
  2. Open a pull request with the middleware refactor.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. Merge to main and verify the deployment in staging before promoting to production.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other middleware or handlers are affected before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

Yes. gin.Default() includes Recovery by default. If you use gin.New(), add gin.Recovery() explicitly. It catches panics and returns 500 instead of crashing the process.

Use the constructor pattern: write a function that accepts dependencies and returns a gin.HandlerFunc closure. This makes dependencies explicit and testable.