Merge branch 'main' into search-template-library

This commit is contained in:
Meet Patel
2023-07-30 23:00:33 +05:30
11 changed files with 401 additions and 61 deletions

View File

@@ -78,6 +78,7 @@ const navigation = [
{ title: "Get Webhook", href: "/docs/webhook-api/get-webhook" },
{ title: "Create Webhook", href: "/docs/webhook-api/create-webhook" },
{ title: "Delete Webhook", href: "/docs/webhook-api/delete-webhook" },
{ title: "Webhook Payload", href: "/docs/webhook-api/webhook-payload" },
],
},
{

View File

@@ -8,24 +8,56 @@ export const meta = {
"Utilize Docker-Compose for easy deployment on your machine. Clone the repo, configure settings, and build the image to access the app on localhost.",
};
At Formbricks, we understand that different users have different needs, and we strive to cater to a wide variety of situations. This is why we provide two ways of running our application using Docker:
At Formbricks, we understand that different users have different needs, and we strive to cater to a wide variety of situations. This is why we provide three ways of running our application:
1. **Fast Setup with a Pre-built Docker Image:** This method is designed for those who want to quickly set up and start using Formbricks without getting into the technicalities of Docker or the build process. When you choose this method, you're using an image that we've already built for you. The pre-built image is ready-to-run, and it only requires minimal configuration on your part. This approach is perfect for getting a functional instance of Formbricks up and running with minimal hassle. It's as easy as downloading the Docker image and firing up the container.
1. **Production Instance Setup with Shell Script on Ubuntu**: If you want to quickly set up a production instance of Formbricks on a server running Ubuntu, we've got you covered! This method utilizes a convenient shell script that takes care of everything, including Docker, Postgres DB, and SSL certificate configuration. The shell script will automatically install all the required dependencies and configure your server, making the process a breeze.
2. **Manual Setup by Building the Docker Image from Source:** This approach provides the flexibility to configure every aspect of your Formbricks instance, including environment variables that need to be set at build time. While we don't recommend changing the source code of Formbricks, this method allows you to set your own configuration that might be necessary for specific deployment needs. Keep in mind that this method requires a more in-depth understanding of Docker and the build process. However, the trade-off is the additional control and flexibility you gain, making it worth considering if you're a more advanced user or have very specific configuration needs.
2. **Fast Setup with a Pre-built Docker Image:** This method is designed for those who want to quickly set up and start using Formbricks without getting into the technicalities of Docker or the build process. When you choose this method, you're using an image that we've already built for you. The pre-built image is ready-to-run, and it only requires minimal configuration on your part. This approach is perfect for getting a functional instance of Formbricks up and running with minimal hassle. It's as easy as downloading the Docker image and firing up the container.
3. **Manual Setup by Building the Docker Image from Source:** This approach provides the flexibility to configure every aspect of your Formbricks instance, including environment variables that need to be set at build time. While we don't recommend changing the source code of Formbricks, this method allows you to set your own configuration that might be necessary for specific deployment needs. Keep in mind that this method requires a more in-depth understanding of Docker and the build process. However, the trade-off is the additional control and flexibility you gain, making it worth considering if you're a more advanced user or have very specific configuration needs.
Please note that regardless of the method you choose, Formbricks is designed to be easy-to-use and flexible. So choose the method that best fits your comfort level and requirements, and start leveraging the power of Formbricks today!
---
## Requirements
## (Production: Ubuntu) Running the Shell Script
This is the quickest way to get Formbricks up and running on an Ubuntu server. The shell script will automatically install all the required dependencies and configure your server, making the process a breeze.
### Requirements
Before you proceed, make sure you have the following:
- A Linux Ubuntu Virtual Machine deployed with SSH access.
- An A record set up to connect a custom domain to your instance. Formbricks will automatically create an SSL certificate for your domain using Let's Encrypt.
## Single Command Setup
Copy and paste the following command into your terminal:
```bash
/bin/sh -c "$(curl -fsSL https://raw.githubusercontent.com/formbricks/formbricks/main/docker/production.sh)"
```
The script will prompt you for the following information:
1. **Overwriting Docker GPG Keys**: If Docker GPG keys already exist, the script will ask if you want to overwrite them.
2. **Email Address**: Provide your email address for SSL certificate registration with Let's Encrypt.
3. **Domain Name**: Enter the domain name that Traefik will use to create the SSL certificate and forward requests to Formbricks.
That's it! After running the command and providing the required information, visit the domain name you entered, and you should see the Formbricks home wizard!
## (Most users: Local Setup) Running the pre-built Docker Image
### Requirements
Ensure `docker` & `docker compose` are installed on your server/system. Both are typically included with Docker utilities, like Docker Desktop and Rancher Desktop.
**Note**: `docker compose` without the hyphen is now the primary method of using docker-compose, according to the Docker documentation.
## (Most users) Running the pre-built Docker Image
This is suitable for those who are testing Formbricks or running it with minimal to no modifications. For this we use the [public Docker image](https://hub.docker.com/r/formbricks/formbricks) and a simple docker-compose file.
1. **Create a New Directory for Formbricks**
@@ -89,6 +121,12 @@ This is suitable for those who are testing Formbricks or running it with minimal
## (Advanced users) Build and Run Formbricks
### Requirements
Ensure `docker` & `docker compose` are installed on your server/system. Both are typically included with Docker utilities, like Docker Desktop and Rancher Desktop.
**Note**: `docker compose` without the hyphen is now the primary method of using docker-compose, according to the Docker documentation.
1. Clone the repository:
```bash
@@ -164,4 +202,16 @@ docker compose logs -f
You can close the logs again with `CTRL + C`.
## Troubleshooting for the Shell Script Setup
If you encounter any issues, consider the following steps:
- **Inbound Rules**: Make sure you have added inbound rules for Port 80 and 443 in your VM's Security Group.
- **A Record**: Verify that you have set up an A record for your domain, pointing to your VM's IP address.
- **Check Docker Instances**: Run `docker ps` to check the status of the Docker instances.
- **Check Formbricks Logs**: Run `cd formbricks && docker compose logs` to check the logs of the Formbricks stack.
export default ({ children }) => <Layout meta={meta}>{children}</Layout>;

View File

@@ -0,0 +1,69 @@
import { Layout } from "@/components/docs/Layout";
import { Fence } from "@/components/shared/Fence";
export const meta = {
title: "Webhook Payload",
description: "Learn how to use the Formbricks Webhook API.",
};
This documentation helps understand the payload structure that will be received when the webhook is triggered in Formbricks.
## An example webhook payload
```
{
"webhookId": "cljwxvjos0003qhnvj2jg4k5i",
"event": "responseCreated",
"data": {
"id": "cljwy2m8r0001qhclco1godnu",
"createdAt": "2023-07-10T14:14:17.115Z",
"updatedAt": "2023-07-10T14:14:17.115Z",
"surveyId": "cljsf3d7a000019cv9apt2t27",
"finished": false,
"data": {
"qumbk3fkr6cky8850bvvq5z1": "Executive"
},
"meta": {
"userAgent": {
"os": "Mac OS",
"browser": "Chrome"
}
},
"personAttributes": {
"email": "test@web.com",
"userId": "THIS-IS-A-VERY-LONG-USER-ID-FOR-TESTING"
},
"person": {
"id": "cljold01t0000qh8ewzigzmjk",
"attributes": {
"email": "test@web.com",
"userId": "THIS-IS-A-VERY-LONG-USER-ID-FOR-TESTING"
},
"createdAt": "2023-07-04T17:56:17.154Z",
"updatedAt": "2023-07-04T17:56:17.154Z"
},
"notes": [],
"tags": []
}
}
```
| Variable | Type | Description |
| --------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| webhookId | String | Webhook's Id |
| event | String | The name of the trigger event [responseCreated, responseUpdated, responseFinished] |
| data | Object | Contains the details of the newly created response. |
| data.id | String | Formbricks Response ID. |
| data.createdAt | String | The timestamp when the response was created. |
| data.updatedAt | String | The timestamp when the response was last updated. |
| data.surveyId | String | The identifier of the survey associated with this response. |
| data.finished | Boolean | A boolean value indicating whether the survey response is marked as finished. |
| data.data | Object | An object containing the response data, where keys are question identifiers, and values are the corresponding answers given by the respondent. |
| data.meta | Object | Additional metadata related to the response, such as the user's operating system and browser information. |
| data.personAttributes | Object | An object with attributes related to the respondent, such as their email and a user ID (if available). |
| data.person | Object | Information about the respondent, including their unique id, attributes, and creation/update timestamps. |
| data.notes | Array | An array of notes associated with the response (if any). |
| data.tags | Array | An array of tags assigned to the response (if any). |
export default ({ children }) => <Layout meta={meta}>{children}</Layout>;

View File

@@ -280,6 +280,7 @@ export default function PreviewSurvey({
brandColor={brandColor}
lastQuestion={idx === questions.length - 1}
onSubmit={gotoNextQuestion}
autoFocus={false}
/>
) : null
)
@@ -307,6 +308,7 @@ export default function PreviewSurvey({
brandColor={brandColor}
lastQuestion={idx === questions.length - 1}
onSubmit={gotoNextQuestion}
autoFocus={false}
/>
) : null
)

View File

@@ -53,16 +53,28 @@ export default function MultipleChoiceMultiForm({
},
};
const updateChoice = (choiceIdx: number, updatedAttributes: any) => {
const newChoices = !question.choices
? []
: question.choices.map((choice, idx) => {
if (idx === choiceIdx) {
return { ...choice, ...updatedAttributes };
}
return choice;
});
updateQuestion(questionIdx, { choices: newChoices });
const updateChoice = (choiceIdx: number, updatedAttributes: { label: string }) => {
const newLabel = updatedAttributes.label;
const oldLabel = question.choices[choiceIdx].label;
let newChoices: any[] = [];
if (question.choices) {
newChoices = question.choices.map((choice, idx) => {
if (idx !== choiceIdx) return choice;
return { ...choice, ...updatedAttributes };
});
}
let newLogic: any[] = [];
question.logic?.forEach((logic) => {
let newL: string | string[] | undefined = logic.value;
if (Array.isArray(logic.value)) {
newL = logic.value.map((value) => (value === oldLabel ? newLabel : value));
} else {
newL = logic.value === oldLabel ? newLabel : logic.value;
}
newLogic.push({ ...logic, value: newL });
});
updateQuestion(questionIdx, { choices: newChoices, logic: newLogic });
};
const addChoice = (choiceIdx?: number) => {

View File

@@ -53,16 +53,28 @@ export default function MultipleChoiceSingleForm({
},
};
const updateChoice = (choiceIdx: number, updatedAttributes: any) => {
const newChoices = !question.choices
? []
: question.choices.map((choice, idx) => {
if (idx === choiceIdx) {
return { ...choice, ...updatedAttributes };
}
return choice;
});
updateQuestion(questionIdx, { choices: newChoices });
const updateChoice = (choiceIdx: number, updatedAttributes: { label: string }) => {
const newLabel = updatedAttributes.label;
const oldLabel = question.choices[choiceIdx].label;
let newChoices: any[] = [];
if (question.choices) {
newChoices = question.choices.map((choice, idx) => {
if (idx !== choiceIdx) return choice;
return { ...choice, ...updatedAttributes };
});
}
let newLogic: any[] = [];
question.logic?.forEach((logic) => {
let newL: string | string[] | undefined = logic.value;
if (Array.isArray(logic.value)) {
newL = logic.value.map((value) => (value === oldLabel ? newLabel : value));
} else {
newL = logic.value === oldLabel ? newLabel : logic.value;
}
newLogic.push({ ...logic, value: newL });
});
updateQuestion(questionIdx, { choices: newChoices, logic: newLogic });
};
const addChoice = (choiceIdx?: number) => {

View File

@@ -11,7 +11,7 @@ import { cn } from "@formbricks/lib/cn";
import { Confetti } from "@formbricks/ui";
import { ArrowPathIcon } from "@heroicons/react/24/solid";
import type { Survey } from "@formbricks/types/surveys";
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
type EnhancedSurvey = Survey & {
brandColor: string;
@@ -38,6 +38,14 @@ export default function LinkSurvey({ survey }: LinkSurveyProps) {
// Create a reference to the top element
const topRef = useRef<HTMLDivElement>(null);
const [autoFocus, setAutofocus] = useState(false);
// Not in an iframe, enable autofocus on input fields.
useEffect(() => {
if (window.self === window.top) {
setAutofocus(true);
}
}, []);
// Scroll to top when the currentQuestion changes
useEffect(() => {
@@ -90,6 +98,7 @@ export default function LinkSurvey({ survey }: LinkSurveyProps) {
brandColor={survey.brandColor}
lastQuestion={lastQuestion}
onSubmit={submitResponse}
autoFocus={autoFocus}
/>
)}
</ContentWrapper>

View File

@@ -9,6 +9,7 @@ interface OpenTextQuestionProps {
onSubmit: (data: { [x: string]: any }) => void;
lastQuestion: boolean;
brandColor: string;
autoFocus?: boolean;
}
export default function OpenTextQuestion({
@@ -16,6 +17,7 @@ export default function OpenTextQuestion({
onSubmit,
lastQuestion,
brandColor,
autoFocus = false,
}: OpenTextQuestionProps) {
const [value, setValue] = useState<string>("");
@@ -35,7 +37,7 @@ export default function OpenTextQuestion({
<div className="mt-4">
{question.longAnswer === false ? (
<input
autoFocus
autoFocus={autoFocus}
name={question.id}
id={question.id}
value={value}
@@ -46,7 +48,7 @@ export default function OpenTextQuestion({
/>
) : (
<textarea
autoFocus
autoFocus={autoFocus}
rows={3}
name={question.id}
id={question.id}

View File

@@ -12,6 +12,7 @@ interface QuestionConditionalProps {
onSubmit: (data: { [x: string]: any }) => void;
lastQuestion: boolean;
brandColor: string;
autoFocus: boolean;
}
export default function QuestionConditional({
@@ -19,6 +20,7 @@ export default function QuestionConditional({
onSubmit,
lastQuestion,
brandColor,
autoFocus,
}: QuestionConditionalProps) {
return question.type === QuestionType.OpenText ? (
<OpenTextQuestion
@@ -26,6 +28,7 @@ export default function QuestionConditional({
onSubmit={onSubmit}
lastQuestion={lastQuestion}
brandColor={brandColor}
autoFocus={autoFocus}
/>
) : question.type === QuestionType.MultipleChoiceSingle ? (
<MultipleChoiceSingleQuestion

View File

@@ -1,45 +1,29 @@
# Formbricks Quickstart Using Docker
# Self Host Formbricks Production Instance
Follow the instructions below to quickly get Formbricks running on your system with Docker. This guide is designed for most users who want a straightforward setup process.
Follow this guide to get your Formbricks instance up and running with a Postgres DB and SSL certificate using a single script:
1. **Create a New Directory for Formbricks**
## Requirements
Open a terminal and create a new directory for Formbricks, then navigate into this new directory:
Before you proceed, make sure you have the following:
```bash
mkdir formbricks-quickstart && cd formbricks-quickstart
```
- A Linux Ubuntu Virtual Machine deployed with SSH access.
2. **Download the Docker-Compose File**
- An A record set up to connect a custom domain to your instance. Formbricks will automatically create an SSL certificate for your domain using Let's Encrypt.
Download the docker-compose file directly from the Formbricks repository:
## Single Command Setup
```bash
curl -o docker-compose.yml https://raw.githubusercontent.com/formbricks/formbricks/docker/main/docker-compose.yml
```
Copy and paste the following command into your terminal:
3. **Generate NextAuth Secret**
```bash
/bin/sh -c "$(curl -fsSL https://raw.githubusercontent.com/formbricks/formbricks/main/docker/production.sh)"
```
Next, you need to generate a NextAuth secret. This will be used for session signing and encryption. The `sed` command below generates a random string using `openssl`, then replaces the `NEXTAUTH_SECRET:` placeholder in the `docker-compose.yml` file with this generated secret:
The script will prompt you for the following information:
```bash
sed -i "/NEXTAUTH_SECRET:$/s/NEXTAUTH_SECRET:.\*/NEXTAUTH_SECRET: $(openssl rand -base64 32)/" docker-compose.yml
```
1. **Overwriting Docker GPG Keys**: If Docker GPG keys already exist, the script will ask if you want to overwrite them.
4. **Start the Docker Setup**
2. **Email Address**: Provide your email address for SSL certificate registration with Let's Encrypt.
You're now ready to start the Formbricks Docker setup. The following command will start Formbricks together with a postgreSQL database using Docker Compose:
3. **Domain Name**: Enter the domain name that Traefik will use to create the SSL certificate and forward requests to Formbricks.
```bash
docker compose up -d
```
The `-d` flag will run the containers in detached mode, meaning they'll run in the background.
5. **Visit Formbricks in Your Browser**
After starting the Docker setup, visit http://localhost:3000 in your browser to interact with the Formbricks application. The first time you access this page, you'll be greeted by a setup wizard. Follow the prompts to define your first user and get started.
Enjoy using Formbricks!
Note: For detailed documentation of local setup, take a look at our [self hosting docs](https://formbricks.com/docs/self-hosting/deployment)
That's it! After running the command and providing the required information, visit the domain name you entered, and you should see the Formbricks home wizard!

196
docker/production.sh Normal file
View File

@@ -0,0 +1,196 @@
#!/bin/env bash
set -e
ubuntu_version=$(lsb_release -a 2>/dev/null | grep -v "No LSB modules are available." | grep "Description:" | awk -F "Description:\t" '{print $2}')
# Friendly welcome
echo "🧱 Welcome to the Formbricks single instance installer"
echo ""
echo "🛸 Fasten your seatbelts! We're setting up your Formbricks environment on your $ubuntu_version server."
echo ""
# Remove any old Docker installations, without stopping the script if they're not found
echo "🧹 Time to sweep away any old Docker installations."
sudo apt-get remove docker docker-engine docker.io containerd runc >/dev/null 2>&1 || true
# Update package list
echo "🔄 Updating your package list."
sudo apt-get update >/dev/null 2>&1
# Install dependencies
echo "📦 Installing the necessary dependencies."
sudo apt-get install -y \
ca-certificates \
curl \
gnupg \
lsb-release >/dev/null 2>&1
# Set up Docker's official GPG key & stable repository
echo "🔑 Adding Docker's official GPG key and setting up the stable repository."
sudo mkdir -m 0755 -p /etc/apt/keyrings >/dev/null 2>&1
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg >/dev/null 2>&1
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null 2>&1
# Update package list again
echo "🔄 Updating your package list again."
sudo apt-get update >/dev/null 2>&1
# Install Docker
echo "🐳 Installing Docker."
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin >/dev/null 2>&1
# Test Docker installation
echo "🚀 Testing your Docker installation."
if docker --version >/dev/null 2>&1; then
echo "🎉 Docker is installed!"
else
echo "❌ Docker is not installed. Please install Docker before proceeding."
exit 1
fi
# Adding your user to the Docker group
echo "🐳 Adding your user to the Docker group to avoid using sudo with docker commands."
sudo groupadd docker >/dev/null 2>&1 || true
sudo usermod -aG docker $USER >/dev/null 2>&1
echo "🎉 Hooray! Docker is all set and ready to go. You're now ready to run your Formbricks instance!"
# Installing Traefik
echo "🚗 Installing Traefik..."
mkdir -p formbricks && cd formbricks
echo "📁 Created Formbricks Quickstart directory at ./formbricks."
# Ask the user for their email address
echo "💡 Please enter your email address for the SSL certificate:"
read email_address
cat <<EOT >traefik.yaml
entryPoints:
web:
address: ":80"
http:
redirections:
entryPoint:
to: websecure
scheme: https
permanent: true
websecure:
address: ":443"
http:
tls:
certResolver: default
providers:
docker:
watch: true
exposedByDefault: false
certificatesResolvers:
default:
acme:
email: $email_address
storage: acme.json
caServer: "https://acme-v01.api.letsencrypt.org/directory"
tlsChallenge: {}
EOT
echo "💡 Created traefik.yaml file with your provided email address."
touch acme.json
chmod 600 acme.json
echo "💡 Created acme.json file with correct permissions."
# Ask the user for their email address
echo "🔗 Please enter your domain name for the SSL certificate (🚨 do NOT enter the protocol (http/https/etc)):"
read domain_name
cat <<EOT >docker-compose.yml
version: "3.3"
x-environment: &environment
environment:
########################################################################
# ------------ MANDATORY (CHANGE ACCORDING TO YOUR SETUP) ------------#
########################################################################
# PostgreSQL DB for Formbricks to connect to
DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/formbricks?schema=public"
# Uncomment to enable a dedicated connection pool for Prisma using Prisma Data Proxy
# Cold boots will be faster and you'll be able to scale your DB independently of your app.
# @see https://www.prisma.io/docs/data-platform/data-proxy/use-data-proxy
# PRISMA_GENERATE_DATAPROXY=true
PRISMA_GENERATE_DATAPROXY:
# NextJS Auth
# @see: https://next-auth.js.org/configuration/options#nextauth_secret
# You can use: $(openssl rand -base64 32) to generate one
NEXTAUTH_SECRET:
# Set this to your public-facing URL, e.g., https://example.com
# You do not need the NEXTAUTH_URL environment variable in Vercel.
NEXTAUTH_URL: "https://$domain_name"
services:
postgres:
restart: always
image: postgres:15-alpine
volumes:
- postgres:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=postgres
formbricks:
restart: always
image: formbricks/formbricks:latest
depends_on:
- postgres
labels:
- "traefik.enable=true" # Enable Traefik for this service
- "traefik.http.routers.formbricks.rule=Host(\`$domain_name\`)" # Replace your_domain_name with your actual domain or IP
- "traefik.http.routers.formbricks.entrypoints=websecure" # Use the websecure entrypoint (port 443 with TLS)
- "traefik.http.services.formbricks.loadbalancer.server.port=3000" # Forward traffic to Formbricks on port 3000
ports:
- 3000:3000
<<: *environment
traefik:
image: "traefik:v2.7"
restart: always
container_name: "traefik"
depends_on:
- formbricks
ports:
- "80:80"
- "443:443"
- "8080:8080"
volumes:
- ./traefik.yaml:/traefik.yaml
- ./acme.json:/acme.json
- /var/run/docker.sock:/var/run/docker.sock:ro
volumes:
postgres:
driver: local
EOT
update_nextauth_secret() {
nextauth_secret=$(openssl rand -base64 32)
sed -i "/NEXTAUTH_SECRET:$/s/NEXTAUTH_SECRET:.\*/NEXTAUTH_SECRET: $nextauth_secret/" docker-compose.yml
}
echo "🚙 Updating NEXTAUTH_SECRET in the Formbricks container..."
while true; do
if update_nextauth_secret; then
echo "🚗 NEXTAUTH_SECRET updated successfully!"
break
else
echo "🚧 Failed to update NEXTAUTH_SECRET. Retrying..."
fi
done
newgrp docker << END
docker compose up -d
echo "🚨 Make sure you have set up the DNS records as well as inbound rules for the domain name and IP address of this instance."
echo ""
echo "🎉 All done! Check the status of Formbricks & Traefik with 'cd formbricks && sudo docker compose ps.'"