How to Create a JWT in Go with golang-jwt
In Go, the golang-jwt/jwt/v5 package creates JSON Web Tokens in two calls: jwt.NewWithClaims builds a token from a signing method and your claims, and SignedString signs it with a key and returns the token string.
Syntax
token := jwt.NewWithClaims(<signing method>, <claims>)
signed, err := token.SignedString(<key>)
| Part | What it does |
|---|---|
<signing method> | The algorithm, such as jwt.SigningMethodHS256. |
<claims> | The claims: a struct that embeds jwt.RegisteredClaims, or a jwt.MapClaims map. |
SignedString(<key>) | Signs the token and returns it as a string, plus an error. For HS256 the key is a []byte. |
From the package documentation: "NewWithClaims creates a new Token with the specified signing method and claims." and "SignedString creates and returns a complete, signed JWT. The token is signed using the SigningMethod specified in the token."
The Example
The example creates a token for the user ada with the role reader, issued now and valid for 10 minutes, signs it with HS256 and prints it.
The key is 32 random bytes, made with openssl rand -base64 32 and written as base64. It sits in the code only so the example runs as it is. A real application loads its key from configuration, such as an environment variable or a secret store, and never keeps it in the source.
Prerequisites
- Go. This guide uses Go 1.27.4.
Step 1: Create the Project
mkdir demo
cd demo
go mod init demo
go get github.com/golang-jwt/jwt/v5
go mod init demo creates a module named demo, and go get adds the package:
go: downloading github.com/golang-jwt/jwt/v5 v5.3.1
go: downloading github.com/golang-jwt/jwt v3.2.2+incompatible
go: added github.com/golang-jwt/jwt/v5 v5.3.1
The second line is Go checking the older module path github.com/golang-jwt/jwt while it works out which module holds the package. Only v5.3.1 is added.
Step 2: Write the Code
Create main.go:

package main
import (
"encoding/base64"
"fmt"
"os"
"time"
"github.com/golang-jwt/jwt/v5"
)
// Claims is what the token says: a role plus the registered claims.
type Claims struct {
Role string `json:"role"`
jwt.RegisteredClaims
}
func main() {
// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
key, err := base64.StdEncoding.DecodeString("VfosHbT9z3nikPe56UUfKL9Y6mF2oOui09j4GCY0AYs=")
if err != nil {
fail(err)
}
now := time.Now()
claims := Claims{
Role: "reader",
RegisteredClaims: jwt.RegisteredClaims{
Subject: "ada",
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(10 * time.Minute)),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString(key)
if err != nil {
fail(err)
}
fmt.Println(signed)
}
// fail prints an error to standard error and stops the program.
func fail(err error) {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
jwt.RegisteredClaims holds the standard claims, such as Subject and ExpiresAt, and embedding it gives Claims all of them. jwt.NewNumericDate turns a time.Time into the Unix-seconds form JWTs use.
Step 3: Run It
go run .
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicmVhZGVyIiwic3ViIjoiYWRhIiwiZXhwIjoxNzk1NjgzMTA1LCJpYXQiOjE3OTU2ODI1MDV9.txSf5lXEIpwCA8b-yCGhItbYicsHnQDyibSDCrC5jCA

go run . compiles the package in this folder and runs it. Your token will differ, because iat and exp hold the time you run it. Decoded from base64url, the header and payload read:
{"alg":"HS256","typ":"JWT"}
{"role":"reader","sub":"ada","exp":1795683105,"iat":1795682505}
The JSON keys come from the struct tags: role from the json:"role" tag, and sub, exp and iat from the tags inside jwt.RegisteredClaims.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Passing the key as a string | key is of invalid type: HMAC sign expects []byte | Pass a []byte |
| A short key | golang-jwt signed with a 5-byte key without complaint, but RFC 7518 requires at least 256 bits for HS256 | Use 32 random bytes or more |
Ignoring the error from SignedString | On an error it returns "", so an empty string goes out as the token | Check err |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
key is of invalid type: HMAC sign expects []byte | The key is a string | Convert or decode it to []byte |
| A claim is missing from the payload | The struct field isn't exported: a lowercase role field was left out, and go vet warned struct field role has json tag but is not exported | Start the field name with a capital letter |
no required module provides package github.com/golang-jwt/jwt/v5 | The module wasn't added | Run go get github.com/golang-jwt/jwt/v5 |
FAQ
Struct or jwt.MapClaims?
A struct gives your claims fixed names and types, checked by the compiler. jwt.MapClaims is a map for claims you only know at run time.
How long should the key be?
At least 32 bytes. RFC 7518, section 3.2: "A key of the same size as the hash output (for instance, 256 bits for "HS256") or larger MUST be used with this algorithm."
Conclusion
Put your claims in a struct that embeds jwt.RegisteredClaims, call jwt.NewWithClaims(jwt.SigningMethodHS256, claims), and SignedString(key) returns the signed token. Pass the key as 32 or more random bytes.
Additional Resources
- golang-jwt/jwt/v5, on pkg.go.dev.
- Signing methods and key types, in the golang-jwt documentation.
