# Feeds

## Creating a Feed

>
> **Info:** When using server-side SDKs, the `user_id` parameter is required in the `getOrCreate` request. It's needed in order to automatically create a user. Client-side SDKs do not require this parameter as the user is authenticated via token.
>

```go label="Go"
// Example 1
response, err := feed.GetOrCreate(context.Background(), &getstream.GetOrCreateFeedRequest{
  UserID: getstream.PtrTo("john"),
})

if err != nil {
  log.Fatal("Error:", err)
}
log.Printf("Success: %+v\n", response)

// Example 2
response2, err := feed.GetOrCreate(context.Background(), &getstream.GetOrCreateFeedRequest{
  UserID: getstream.PtrTo("john"),
  Data: &getstream.FeedInput{
    Description: getstream.PtrTo("My personal feed"),
    Name:        getstream.PtrTo("John Hikes"),
    Visibility:  getstream.PtrTo("public"),
    FilterTags:  []string{"tech", "hiking", "cooking"},
  }})
if err != nil {
  log.Fatal("Error creating advanced feed:", err)
}
log.Printf("Success: %+v\n", response2)
```

## Built-in feed groups

| Group          | Description                                                                                                                    |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `user`         | A feed setup for the content a user creates. Typically you add activities here when someone writes a post                      |
| `timeline`     | The timeline feed is used when you're following. So if user Charlie is following John, timeline:charlie would follow user:john |
| `foryou`       | A version of the timeline feed that adds popular content, and prioritizes popularity over recency                              |
| `notification` | A notification feed. Think of the bell icon you see in most apps                                                               |
| `story`        | A feed set up for users to post story activities (activities with expiration data)                                             |
| `stories`      | A timeline feed which can be used to follow other users' stories.                                                              |

## Reading a Feed

For high-traffic feeds many users read the same way, prefer server-side reads from your backend. If Stream has enabled [hot feed cache](https://getstream.io/activity-feeds/docs/node/hot-feed-cache/) for a feed, reads must be server-side for the cache to apply.

Here is a basic example of how to read a feed:

```go label="Go"
feed := client.Feeds().Feed("user", "john")
response, err := feed.GetOrCreate(context.Background(), &getstream.GetOrCreateFeedRequest{
  UserID: getstream.PtrTo("john"),
})
if err != nil {
  log.Fatal("Error calling getOrCreate:", err)
}

feedData := response.Data.Feed
activities := response.Data.Activities
members := response.Data.Members
```

The response will contain the following data.

You have more options when reading a feed, let's go over a few:

```go label="Go"
feed := client.Feeds().Feed("user", "jack")
request := &getstream.GetOrCreateFeedRequest{
  Limit:  intPtr(10),
  UserID: stringPtr("<user id>"),
  View:   stringPtr("myview"),
  Filter: getstream.PtrTo(map[string]any{
    "filter_tags": []string{"green"}, // filter activities with filter tag green
  }),
  ExternalRanking: getstream.PtrTo(map[string]any{
    "user_score": 0.8, // additional data used for ranking
  }),
  FollowersPagination: &getstream.PagerRequest{
    Limit: intPtr(10),
  },
  FollowingPagination: &getstream.PagerRequest{
    Limit: intPtr(10),
  },
  MemberPagination: &getstream.PagerRequest{
    Limit: intPtr(10),
  },
}
response, err := feed.GetOrCreate(context.Background(), request)
```

## Enrichment Options

You can control how activities are enriched when reading a feed by providing `enrichment_options` to the `getOrCreate` request. This allows you to customize which fields and related data are included in the response.

### EnrichmentOptions

| Name | Type | Description | Constraints |
| --- | --- | --- | --- |
| `enrich_own_followings` | `boolean` | Default: false. When true, includes fetching and enriching own_followings (follows where activity author's feeds follow current user's feeds). | - |
| `include_flat_activities` | `boolean` | Controls the top-level flat 'activities' array for aggregated feeds. For new apps, defaults to false (excluded); set to true to include. For older apps, defaults to true (included) for backward compatibility; set to false to exclude. | - |
| `include_score_vars` | `boolean` | Default: false. When true, includes score_vars in activity responses containing variable values used at ranking time. | - |
| `skip_activity` | `boolean` | Default: false. When true, skips all activity enrichments. | - |
| `skip_activity_collections` | `boolean` | Default: false. When true, skips enriching collections on activities. | - |
| `skip_activity_comments` | `boolean` | Default: false. When true, skips enriching comments on activities. | - |
| `skip_activity_current_feed` | `boolean` | Default: false. When true, skips enriching current_feed on activities. Note: CurrentFeed is still computed for permission checks, but enrichment is skipped. | - |
| `skip_activity_mentioned_users` | `boolean` | Default: false. When true, skips enriching mentioned users on activities. | - |
| `skip_activity_own_bookmarks` | `boolean` | Default: false. When true, skips enriching own bookmarks on activities. | - |
| `skip_activity_parents` | `boolean` | Default: false. When true, skips enriching parent activities. | - |
| `skip_activity_poll` | `boolean` | Default: false. When true, skips enriching poll data on activities. | - |
| `skip_activity_reactions` | `boolean` | Default: false. When true, skips fetching and enriching latest and own reactions on activities. Note: If reactions are already denormalized in the database, they will still be included. | - |
| `skip_activity_refresh_image_urls` | `boolean` | Default: false. When true, skips refreshing image URLs on activities. | - |
| `skip_all` | `boolean` | Default: false. When true, skips all enrichments. | - |
| `skip_feed_member_user` | `boolean` | Default: false. When true, skips enriching user data on feed members. | - |
| `skip_followers` | `boolean` | Default: false. When true, skips fetching and enriching followers. Note: If followers_pagination is explicitly provided, followers will be fetched regardless of this setting. | - |
| `skip_following` | `boolean` | Default: false. When true, skips fetching and enriching following. Note: If following_pagination is explicitly provided, following will be fetched regardless of this setting. | - |
| `skip_own_capabilities` | `boolean` | Default: false. When true, skips computing and including capabilities for feeds. | - |
| `skip_own_follows` | `boolean` | Default: false. When true, skips fetching and enriching own_follows (follows where user's feeds follow target feeds). | - |
| `skip_pins` | `boolean` | Default: false. When true, skips enriching pinned activities. | - |

>
> **Info:** **Performance Optimization**: Enrichment options allow you to skip specific enrichments to improve performance.
>
> **Important Notes**:
>
> - **Reactions**: If `skip_activity_reactions` is set to `true`, the expensive enrichment step is skipped. However, if reactions are already denormalized in the database, they will still be included in the response. This option only skips the expensive enrichment step but does not remove already-loaded data for performance reasons.
>
> - **Followers/Following**: If `skip_followers` or `skip_following` is set to `true`, fetching and enriching followers or following is skipped. However, if `followers_pagination` or `following_pagination` is explicitly provided in the request, followers or following will be fetched regardless of this setting. This ensures that explicit pagination requests are always honored.
>

### Example

```go label="Go"
feed := client.Feeds().Feed("user", "jack")
request := &getstream.GetOrCreateFeedRequest{
  UserID: stringPtr("<user id>"),
  EnrichmentOptions: &getstream.EnrichmentOptions{
    // Configure enrichment options here
  },
}
response, err := feed.GetOrCreate(context.Background(), request)
```

## Feed Pagination

Here is how you can read the next page on the feed:

```go label="Go"
feed := client.Feeds().Feed("user", "john")

// First page
firstPage, err := feed.GetOrCreate(context.Background(), &getstream.GetOrCreateFeedRequest{
  Limit:  getstream.PtrTo(10),
  UserID: getstream.PtrTo("john"),
})
if err != nil {
  log.Fatal("Error getting first page:", err)
}

// Second page request using next cursor
nextPage, err := feed.GetOrCreate(context.Background(), &getstream.GetOrCreateFeedRequest{
  Next:   firstPage.Data.Next,
  Limit:  getstream.PtrTo(10),
  UserID: getstream.PtrTo("john"),
})
if err != nil {
  log.Fatal("Error getting next page:", err)
}

log.Printf("First page activities count: %d", len(firstPage.Data.Activities))
log.Printf("Next page activities count: %d", len(nextPage.Data.Activities))
```

When using `external_ranking` with [hot feed cache](https://getstream.io/activity-feeds/docs/node/hot-feed-cache/), pass the same `external_ranking` values on every page. Changing or dropping them mid-pagination discards the cached snapshot for that page. See [Pagination](https://getstream.io/activity-feeds/docs/node/hot-feed-cache/#pagination) and [External ranking](https://getstream.io/activity-feeds/docs/node/hot-feed-cache/#external-ranking).

## Filters

`filter` provides a performant way to read a feed, and only select activities that match a given filter.

>
> **Info:** Please note that filtering is typically used for fields with fixed value sets (for example `filter_tags`), for text based search, you should check out [query activities endpoint](https://getstream.io/activity-feeds/docs/go-golang/query-activities/)
>

### Examples

```go label="Go"
ctx := context.Background()
// Create feed
feed := client.Feeds().Feed("user", "john")

// Create activities
activities := []getstream.ActivityRequest{
	{
		Feeds:      []string{"user:john"},
		Type:       "post",
		Text:       stringPtr("first"),
		FilterTags: []string{"green", "blue"},
		UserID:     stringPtr("john"),
	},
	{
		Feeds:      []string{"user:john"},
		Type:       "post",
		Text:       stringPtr("second"),
		FilterTags: []string{"yellow", "blue"},
		UserID:     stringPtr("john"),
	},
	{
		Feeds:      []string{"user:john"},
		Type:       "post",
		Text:       stringPtr("third"),
		FilterTags: []string{"orange"},
		UserID:     stringPtr("john"),
	},
}

// Upsert activities
_, err = client.Feeds().UpsertActivities(ctx, &getstream.UpsertActivitiesRequest{
	Activities: activities,
})
if err != nil {
	log.Fatal("Error upserting activities:", err)
}

// Get or create feed with filter
response, err := feed.GetOrCreate(ctx, &getstream.GetOrCreateFeedRequest{
	Filter: getstream.PtrTo(map[string]any{
		"filter_tags": []string{"blue"},
	}),
	UserID: stringPtr("john"),
})
if err != nil {
	log.Fatal("Error getting or creating feed:", err)
}

log.Printf("Feed response: %+v", len(response.Data.Activities))
```

The filter syntax also supports `$or` and `$and`, so here's an example that's a little more complicated:

```go label="Go"
// Get all the activities where filter tags contain both "green" and "orange"
feed := client.Feeds().Feed("user", "john")
response, err := feed.GetOrCreate(ctx, &getstream.GetOrCreateFeedRequest{
    Filter: getstream.PtrTo(map[string]any{
        "$and": []map[string]any{
            {"filter_tags": []string{"green"}},
            {"filter_tags": []string{"orange"}},
        },
    }),
    UserID: getstream.PtrTo("john"),
})
if err != nil {
    log.Fatal("Error getting feed with filter:", err)
}
log.Printf("Activities: %+v", response.Data.Activities)
```

### Supported filters

What filters you can use when reading a feed depends on the feed group (or view, if provided) configuration.

The [activity selectors page](https://getstream.io/activity-feeds/docs/go-golang/activity-selectors/) explains this in detail, but some quick examples: the `user` group uses `current` selector, and the `timeline` group the `following` selector by default.

The following `filter` options are available for the `following` selector:

| name          | type                      | description            | supported operations      | example                                                  |
| ------------- | ------------------------- | ---------------------- | ------------------------- | -------------------------------------------------------- |
| `id`          | string or list of strings | The ID of the activity | `$in`, `$eq`              | `{ id: { $in: [ 'abc', 'xyz' ] } }`                      |
| `filter_tags` | list of strings           | Tags for filtering     | `$eq`, `$contains`, `$in` | `{ filter_tags: { $in: [ 'categoryA', 'categoryB' ] } }` |

The following `filter` options are available for the `current`, `popular`, `interest`, `proximity` and `query` selectors:

| name            | type                                              | description                                                      | supported operations                       | example                                                                                      |
| --------------- | ------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------- |
| `id`            | string or list of strings                         | The ID of the activity                                           | `$in`, `$eq`                               | `{ id: { $in: [ 'abc', 'xyz' ] } }`                                                          |
| `activity_type` | string or list of strings                         | The type of the activity                                         | `$in`, `$eq`                               | `{ activity_type: { $in: [ 'abc', 'xyz' ] } }`                                               |
| `user_id`       | string or list of strings                         | The ID of the user who created the activity                      | `$in`, `$eq`                               | `{ user_id: { $in: [ 'abc', 'xyz' ] } }`                                                     |
| `text`          | string                                            | The text content of the activity                                 | `$eq`, `$q`, `$autocomplete`               | `{ text: { $q: 'popularity' } }`                                                             |
| `search_data`   | object                                            | The extra metadata for search indexing                           | `$contains`, `$path_exists`                | `{ search_data: { $contains: { 'category': 'sports', 'status': 'active' } } }`               |
| `interest_tags` | list of strings                                   | Tags for user interests                                          | `$eq`, `$contains`                         | `{ interest_tags: { $in: [ 'sports', 'music' ] } }`                                          |
| `filter_tags`   | list of strings                                   | Tags for filtering                                               | `$eq`, `$contains`, `$in`                  | `{ filter_tags: { $in: [ 'categoryA', 'categoryB' ] } }`                                     |
| `created_at`    | string, must be formatted as an RFC3339 timestamp | The time the activity was created                                | `$eq`, `$gt`, `$lt`, `$gte`, `$lte`        | `{ created_at: { $gte: '2023-12-04T09:30:20.45Z' } }`                                        |
| `popularity`    | number                                            | The popularity score of the activity                             | `$eq`, `$ne`, `$gt`, `$lt`, `$gte`, `$lte` | `{ popularity: { $gte: 70 } }`                                                               |
| `near`          | object                                            | GEO point and a distance (in km) to search for activities within | `$eq`                                      | `{ near: { $eq: { lat: 40.0, lng: -74.0, distance: 200 } } }`                                |
| `within_bounds` | object                                            | GEO bounds to search for activities within                       | `$eq`                                      | `{ within_bounds: { $eq: { ne_lat: 40.0, ne_lng: -115.0, sw_lat: 32.0, sw_lng: -125.0 } } }` |

When filtering by `filter_tags`, a plain array (or `$eq`) uses **AND-logic**: the activity must contain **all** of the specified tags. Use `$in` if you want **OR-logic**, where the activity must contain **any** of the specified tags.

The filter syntax also supports `$or` and `$and`:

```go label="Go"
// Get all the activities where filter tags contain both "green" and "orange"
filter := map[string]any{
  "$and": []map[string]any{
    {"filter_tags": []string{"green"}},
    {"filter_tags": []string{"orange"}},
  },
}
```

When providing `filter` to read a feed, activity selector filters on group/view level are ignored.

## Overview of built-in fields

### GetOrCreateFeedResponse

| Name | Type | Description | Constraints |
| --- | --- | --- | --- |
| `activities` | `ActivityResponse[]` | - | Required |
| `aggregated_activities` | `AggregatedActivityResponse[]` | - | Required |
| `created` | `boolean` | - | Required |
| `duration` | `string` | Duration of the request in milliseconds | Required |
| `feed` | `FeedResponse` | - | Required |
| `followers` | `FollowResponse[]` | - | Required |
| `followers_pagination` | `PagerResponse` | - | - |
| `following` | `FollowResponse[]` | - | Required |
| `following_pagination` | `PagerResponse` | - | - |
| `member_pagination` | `PagerResponse` | - | - |
| `members` | `FeedMemberResponse[]` | - | Required |
| `next` | `string` | - | - |
| `notification_status` | `NotificationStatusResponse` | - | - |
| `pinned_activities` | `ActivityPinResponse[]` | - | Required |
| `prev` | `string` | - | - |

### FeedResponse

| Name | Type | Description | Constraints |
| --- | --- | --- | --- |
| `activity_count` | `integer` | - | Required |
| `created_at` | `number` | When the feed was created | Required |
| `created_by` | `UserResponse` | User who created the feed | Required |
| `custom` | `object` | Custom data for the feed | - |
| `deleted_at` | `number` | When the feed was deleted | - |
| `description` | `string` | Description of the feed | Required |
| `feed` | `string` | Fully qualified feed ID (group_id:id) | Required |
| `filter_tags` | `string[]` | Tags used for filtering feeds | - |
| `follower_count` | `integer` | Number of followers of this feed | Required |
| `following_count` | `integer` | Number of feeds this feed follows | Required |
| `group_id` | `string` | Group this feed belongs to | Required |
| `id` | `string` | Unique identifier for the feed | Required |
| `location` | `Location` | Geographic location for the feed | - |
| `member_count` | `integer` | Number of members in this feed | Required |
| `name` | `string` | Name of the feed | Required |
| `own_capabilities` | `FeedOwnCapability[]` | Capabilities the current user has for this feed | - |
| `own_followings` | `FollowResponse[]` | Follow relationships where the feed owner’s feeds are following the current user's feeds | - |
| `own_follows` | `FollowResponse[]` | Follow relationships where the current user's feeds are following this feed | - |
| `own_membership` | `FeedMemberResponse` | Membership information for the current user in this feed | - |
| `pin_count` | `integer` | Number of pinned activities in this feed | Required |
| `updated_at` | `number` | When the feed was last updated | Required |
| `visibility` | `string (public, visible, followers, members, private)` | Visibility setting for the feed | - |

## Updating a Feed

The `updateFeed` endpoint performs a partial update: only the fields you include in the request are changed, and each of those fields is completely overwritten.

```go label="Go"
response, err := feed.Update(context.Background(), &getstream.UpdateFeedRequest{
  CreatedByID: getstream.PtrTo("josh"),
  Name:        getstream.PtrTo("Updated feed name"),
  FilterTags:  getstream.PtrTo([]string{"tech", "hiking", "cooking"}),
  Custom:      getstream.PtrTo(map[string]any{"color": "blue"}),
})
if err != nil {
  log.Fatal("Error updating feed:", err)
}
```

### Clearing a feed's location

Since `updateFeed` is a partial update, omitting `location` from the request leaves it unchanged. To explicitly remove a feed's location, set `clear_location` to `true`:

```go label="Go"
response, err := feed.Update(context.Background(), &getstream.UpdateFeedRequest{
  ClearLocation: getstream.PtrTo(true),
})
```

>
> **Warning:** `clear_location` and `location` cannot be used together in the same request. The API will return an error if both are provided.
>

### Changing visibility

Changing visibility has dedicated behavior and SDK examples, including how `pending_follows_action` works when loosening from `followers`.

See [Changing Feed Visibility](https://getstream.io/activity-feeds/docs/node/changing-feed-visibility/) for details.

## Deleting a Feed

>
> **Danger:** Deleting a feed is an irreversible operation. This goes for **both soft and hard deletes**.
>

Deleting a feed will cascade delete the following entities:

- Follows - any follow relationship this feed is part of will be deleted
- Feed members
- Pinned activities
- Activity marks (read/seen)
- Activities - the following will be deleted for each activity
  - Reactions
  - Bookmarks
  - Comments - the following will be deleted for each comment
    - Reactions

The deletion of a feed will be done asynchronously. If the endpoint is called server side a `task_id` is returned and you
can use this task ID to [track the deletion process](https://getstream.io/docs/platform/async-operations/).

The difference between a hard and soft delete is that soft deleting will soft delete the entities that supports this.
These are `feeds`, `activities` and `comments`. Soft deleted `activities` will retain their `reactions` and `bookmarks` until hard deleted. Soft deleted `comments` will retain their `reactions` until hard deleted.
This means that this data can still be exported with the [export endpoint](https://getstream.io/docs/platform/gdpr/#exporting-feeds-data).

```go label="Go"
// Soft delete a feed
response, err := feed.Delete(context.Background(), &getstream.DeleteFeedRequest{
    HardDelete: getstream.PtrTo(false),
})

// Hard delete a feed
response, err := feed.Delete(context.Background(), &getstream.DeleteFeedRequest{
    HardDelete: getstream.PtrTo(true),
})

// Check task progress (you need to poll GetTask)
taskResponse, err := client.GetTask(context.Background(), response.Data.TaskID, &getstream.GetTaskRequest{})
fmt.Println(taskResponse.Data.Status == "completed")
```

## Batch create and delete

You can create and delete multiple feeds in a single request using server-side SDKs. Both batch endpoints support a maximum of 100 feeds per request.

```go label="Go"
feeds := make([]getstream.FeedRequest, 100)
for i := 0; i < 100; i++ {
  feeds[i] = getstream.FeedRequest{
    FeedID:      fmt.Sprintf("feed_%d", i),
    FeedGroupID: "user",
    Name:        getstream.PtrTo(fmt.Sprintf("Feed %d", i)),
    Visibility:  getstream.PtrTo("public"),
  }
}
response, err := client.Feeds().CreateFeedsBatch(ctx, &getstream.CreateFeedsBatchRequest{Feeds: feeds})
if err != nil {
  log.Fatal(err)
}
feedIDs := make([]string, len(response.Data.Feeds))
for i, f := range response.Data.Feeds {
  feedIDs[i] = f.Feed
}
_, err = client.Feeds().DeleteFeedsBatch(ctx, &getstream.DeleteFeedsBatchRequest{
  Feeds:     feedIDs,
  HardDelete: getstream.PtrTo(true),
})
if err != nil {
  log.Fatal(err)
}
```

---

For the most recent version of this documentation, visit [https://getstream.io/activity-feeds/docs/go-golang/feeds/](https://getstream.io/activity-feeds/docs/go-golang/feeds/).