Skip to content

Get started with Go

Arcjet is the AI agent runtime security platform. Discover the agents running in your organization, enforce policy across every action, prompt, and tool call, and keep the evidence to prove what happened. Detect prompt injection, authorize agent tool calls, redact PII, and block bots and abuse.

This guide shows you how to add Arcjet to your application. For an AI agent framework it publishes one policy and guards one tool call with it. For an HTTP framework it blocks automated clients that inflate costs and enforces per-user token budgets. To secure Claude Code, GitHub Copilot, Muse Code, OpenAI Codex, or Cursor, which need no SDK, see Secure coding agents.

In your project root, run the following:

In your project root, add the Arcjet Go SDK:

Terminal window
go get github.com/arcjet/arcjet-go

The SDK requires Go 1.25 or later.

  • Go 1.25 or later

Create a free Arcjet account then follow the instructions to add a site and get a key.

Set ARCJET_KEY in your environment. NewClient and NewGuardClient read it when Key is empty. The Go SDK does not read ARCJET_ENV.

.env
# Arcjet key for your site (from <https://console.arcjet.com>).
# More info: <https://docs.arcjet.com/environment#arcjet-key>.
ARCJET_KEY=ajkey_yourkey

This adds Arcjet to your application code, where it can see who is acting and what they are asking for.

Create a new file at main.go with the contents:

main.go
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
"github.com/arcjet/arcjet-go"
)
var arcjetKey = func() string {
key := os.Getenv("ARCJET_KEY")
if key == "" {
log.Fatal("ARCJET_KEY is required. Get one with: arcjet sites get-key" +
" or from https://app.arcjet.com")
}
return key
}()
// Create a single Arcjet client and reuse it across requests.
var aj = must(arcjet.NewClient(arcjet.Config{
Key: arcjetKey,
Rules: []arcjet.Rule{
// Detect and block prompt injection attacks in user messages.
arcjet.DetectPromptInjection(arcjet.PromptInjectionOptions{
Mode: arcjet.ModeLive,
}),
// Rate limit by token budget — refill 5 tokens every 10 seconds.
arcjet.TokenBucket(arcjet.TokenBucketOptions{
Mode: arcjet.ModeLive,
Characteristics: []string{"userId"},
RefillRate: 5,
Interval: 10 * time.Second,
Capacity: 10,
}),
// Block automated clients. Empty allow list = block all bots.
arcjet.DetectBot(arcjet.BotOptions{
Mode: arcjet.ModeLive,
Allow: []string{},
}),
// Protect against common web attacks (SQLi, XSS, and similar).
arcjet.Shield(arcjet.ShieldOptions{Mode: arcjet.ModeLive}),
},
}))
type chatRequest struct {
Message string `json:"message"`
}
func chat(w http.ResponseWriter, r *http.Request) {
var body chatRequest
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
userID := "user_123" // Replace with a real user ID from the session.
decision, err := aj.Protect(
r.Context(),
r,
arcjet.WithRequested(5), // tokens consumed per request
arcjet.WithCharacteristics(map[string]string{"userId": userID}),
arcjet.WithDetectPromptInjectionMessage(body.Message),
)
if err != nil {
// Arcjet fails open — log and continue serving.
log.Printf("arcjet: %v", err)
} else if decision.IsDenied() {
status := http.StatusForbidden
if decision.Reason.IsRateLimit() {
status = http.StatusTooManyRequests
} else if decision.Reason.IsPromptInjection() {
status = http.StatusBadRequest
}
http.Error(w, "denied", status)
return
}
// Safe to pass body.Message to your LLM.
_ = json.NewEncoder(w).Encode(map[string]string{"reply": "..."})
}
func main() {
http.HandleFunc("/chat", chat)
log.Fatal(http.ListenAndServe(":8000", nil))
}
func must[T any](v T, err error) T {
if err != nil {
log.Fatal(err)
}
return v
}

4. Start app

Terminal window
go run .

Send a chat message:

Terminal window
curl -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{"message": "What is the capital of France?"}'

Visit http://localhost:8000/chat a few times to hit the rate limit. You get a 403 response from curl because curl is considered a bot by default (customizable).

The requests also appear in the Arcjet dashboard.

Do I need to run any infrastructure, such as Redis?

No, Arcjet handles all the infrastructure for you so you don't need to worry about deploying global Redis clusters, designing data structures to track rate limits, or keeping security detection rules up to date.

What is the performance overhead?

Arcjet SDK tries to do as much as possible asynchronously and locally to minimize latency for each request. Where decisions can be made locally or previous decisions are cached in-memory, latency is usually <1ms.

When a call to the Cloud API is required, such as when tracking a rate limit in a serverless environment, there is some additional latency before a decision is made. The Cloud API has been designed for high performance and low latency, and is deployed to multiple regions around the world. The SDK will automatically use the closest region which means the total overhead is typically no more than 20-30ms, often significantly less.

What happens if Arcjet is unavailable?

Where a decision has been cached locally, such as blocking a client, Arcjet will continue to function even if the service is unavailable.

If a call to the Cloud API is needed and there is a network problem or Arcjet is unavailable, the default behavior is to fail open and allow the request. You have control over how to handle errors, including choosing to fail close if you prefer. See the reference docs for details.

How does Arcjet protect me against DDoS attacks?

Network layer attacks tend to be generic and high volume, so these are best handled by your hosting platform. Most cloud providers include network DDoS protection by default.

Arcjet sits closer to your application so it can understand the context. This is important because some types of traffic may not look like a DDoS attack, but can still have the same effect. For example, a customer making too many API requests and affecting other customers, or large numbers of signups from disposable email addresses.

Network-level DDoS protection tools find it difficult to protect against this type of traffic because they don't understand the structure of your application. Arcjet can help you to identify and block this traffic by integrating with your codebase and understanding the context of the request, such as the customer ID or the sensitivity of the API route.

Volumetric network attacks are best handled by your hosting provider. Application level attacks need to be handled by the application. That's where Arcjet helps.

Need help with anything? Email us or join our Discord to get support from our engineering team.