Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SvelteKit, Vite, HMR & Devilbox #797

Open
robots4life opened this issue Mar 19, 2021 · 34 comments
Open

SvelteKit, Vite, HMR & Devilbox #797

robots4life opened this issue Mar 19, 2021 · 34 comments
Assignees

Comments

@robots4life
Copy link

robots4life commented Mar 19, 2021

https://kit.svelte.dev/ is almost out and I'd like to get it going with Devilbox. ❤️

Quite simple, running HMR on wss://devilskit.loc:24678 does not work.

Please check this example repo https://github.com/robots4life/devilskit to reproduce the error I am getting.

There is also a video of the error here https://github.com/robots4life/devilskit/tree/main/video_of_error.

All files are included in the example repo here https://github.com/robots4life/devilskit/tree/main/.devilbox and here https://github.com/robots4life/devilskit/tree/main/devilbox_compose.

Inviting the usual suspects.. @boumanb @science695.

@robots4life
Copy link
Author

robots4life commented Mar 20, 2021

Further research shows that when using HTTPD_SERVER=nginx-stable in the .env file the https://devilskit.loc site just shows Upgrade Required meaning NGINX might not have support for HTTP/2.0 enabled.

When choosing HTTPD_SERVER=apache-2.4 the issue with continuos reloads persists due to wss://devilskit.loc:24678 not working.

edit:
In fact when going to http://localhost:24678 on either NGINX stable or Apache 2.4, Upgrade Required is given as error message.

@robots4life
Copy link
Author

robots4life commented Mar 21, 2021

vitejs/vite#677 (comment) is possibly very related to this. The wss on port 24678 needs to be proxied to the PHP container as well.

How do I need to change the vhost template files to get such a setup going please?

I tried this for the NGINX template but am now getting a 502 on the wsdev location.

vhost: |
    server {
        listen       __PORT____HTTP_PROTO____DEFAULT_VHOST__;
        server_name  __VHOST_NAME__;

        access_log   "__ACCESS_LOG__" combined;
        error_log    "__ERROR_LOG__" warn;

        # Reverse Proxy definition (Ensure to adjust the port, currently '3000')
        location / {
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_pass http://php:3000;
        }

        location /wsdev/ {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_pass http://php:24678/;
        }

    __REDIRECT__
    __SSL__
    __ALIASES__
    __DENIES__
    __SERVER_STATUS__
        # Custom directives
    __CUSTOM__
    }

@boumanb
Copy link

boumanb commented Mar 21, 2021

Hi there @robots4life,

I suppose you have a docker-compose.override.yml in your Devilbox root folder? If so, try adding the following under services: (if you already have a php directive just add the ports so that they are exposed to the host machine):

php:
    ports:
      # ---- Format: ----
      # [HOST-ADDR : ] HOST-PORT : DOCKER-PORT
      - 24678:24678

If you don't have a docker-compose.override.yml please create one and add the following:

# IMPORTANT: The version must match the version of docker-compose.yml
---
version: '2.3'
services:
  php:
    ports:
      # ---- Format: ----
      # [HOST-ADDR : ] HOST-PORT : DOCKER-PORT
      - 24678:24678

When finished please restart Devilbox and see if everything works fine. You can revert the changes that you've made to the NGINX template. I suppose this is all you need to resolve your problem; exposing the proper port to your host machine.

Please let me know how this works out for you!

@robots4life
Copy link
Author

robots4life commented Mar 21, 2021

@boumanb 👋
Here is the thing. The app goes over 3000 and HMR over the secure websocket port 24678. I have both ports opened in the docker-compose.override.yml file. This is also included in the demo repo here https://github.com/robots4life/devilskit/blob/main/devilbox_compose/docker-compose.override.yml but obviously have that file in the devilbox root directory.

version: '2.3'
services:
  php:
    ports:
      # ---- Format: ----
      # [HOST-ADDR : ] HOST-PORT : DOCKER-PORT
      - 24678:24678
      - 3000:3000

If I forward 3000 in the NGINX template wss://devilskit.loc:24678 won't work. It will keep reloading the page as it cannot connect to it, at least not over wss.

If I specify ws in https://github.com/robots4life/devilskit/blob/main/vite.config.js but have the site on https://devilskit.loc it will tell me the connection is not secure, obvious result there.

However everything works just fine over http://devilkit.loc with ws.

Screenshot_20210321_140737

Check this video to see what happens with wss enabled. https://github.com/robots4life/devilskit/blob/main/video_of_error/2021-03-19%2016-17-11.mkv

If I forward 24678 in the NGINX template then I just get Upgrade Required when visiting https://devilkit.loc. The app does not load at all, this despite both ports 3000 and 24678 opened.

Screenshot_20210321_124925
Screenshot_20210321_124953

Clone the repo https://github.com/robots4life/devilskit, npm install, npm run dev, you will see what happens. I think I need two ports proxied, 3000 and 24678 in the NGINX and respectively, Apache templates.

If you look at https://vitejs.dev/config/#server-hmr options are given as to where HRM runs. Here https://github.com/robots4life/devilskit/blob/main/vite.config.js you can see the different approaches I have tried out to get wss going.

Simply uncommenting/commenting this line https://github.com/robots4life/devilskit/blob/main/src/routes/index.svelte#L8 should make the paragraph appear/disappear without a reload.

One can specify a path, and perhaps setting the proxy to that path in the vhost template and adding the 24678 proxy port might make it work. However I am not sure about how to edit the vhost templates for either Apache or NGINX.

        location /wss/ {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_pass http://php:24678/;
        }

In this comment vitejs/vite#677 (comment) someone seems to get things going, but this does not seem to apply to how Devilbox sets up things.

Someone suggested to try out this NGINX config but there seem to be errors with that as well.

server {
    listen       24678 ssl http2;
    server_name  __VHOST_NAME__;

    ssl_certificate           __SSL_PATH_CRT__;
    ssl_certificate_key       __SSL_PATH_KEY__;
    
    location /wss/ {
        proxy_pass   http://php:24678;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

@boumanb
Copy link

boumanb commented Apr 18, 2021

Finally made some time to investigate this. Sorry for my earlier response. I got things up and running locally using ws just like you. When switching to wss I get the same reloading behaviour. Firefox throws a SSL_ERROR_RX_RECORD_TOO_LONG which indicates that something is wrong with the server serving unsecure data over a secure connection.

I have taken a look at vitejs/vite#1992 and I hope it fixes the problem. I'm not able to dive in deeper at this moment.

Good job on providing all the things needed for reproducing the issue!

@robots4life
Copy link
Author

It is exactly that issue with Vite so far not supporting wss, not the only one waiting for that pull request to go through.. 🕦 Thank you for confirming the bug on their end. As soon as the request is merged I will add more details here and then close the issue.

@robots4life
Copy link
Author

SvelteKit now works with Devilbox, secure local dev domain and HMR!

svelte.config.js

import { readFileSync } from 'fs';

/** @type {import('@sveltejs/kit').Config} */
const config = {
	kit: {
		// hydrate the <div id="svelte"> element in src/app.html
		target: '#svelte',
		vite: () => ({
			server: {
				host: '0.0.0.0',
				port: 3000,
				https: {
					key: readFileSync('/shared/httpd/devilbox/ca/certs/mass/skdevkit.loc.key'),

					cert: readFileSync('/shared/httpd/devilbox/ca/certs/mass/skdevkit.loc.crt')
				},
				hmr: {
					host: 'skdevkit.loc',
					protocol: 'wss',
					port: 24678
				}
			}
		})
	}
};
export default config;

npm run dev -- --host 0.0.0.0

vitejs/vite#1992 is solved, thx to the Vite team!

@robots4life
Copy link
Author

A heads up on #709 (comment).

I had to run

sudo find . -type f -exec chmod 664 {} +

and

sudo chown 1000:1000 *

on the ${DEVILBOX_PATH}/ca/certs directory for latest versions of Svelte and SvelteKit to be able to access the .key and .crt file from Node.

Running ./check-config.sh in the Devilbox installation directory then also did not complain about issues any more.

@robots4life
Copy link
Author

Current status.

npm ls

├── @sveltejs/[email protected]
├── @sveltejs/[email protected]
├── @sveltejs/[email protected]
├── @sveltejs/[email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

svelte.config.js

import { readFileSync } from 'fs';

import adapter from '@sveltejs/adapter-static';

/** @type {import('@sveltejs/kit').Config} */
const config = {
	kit: {
		// Adapter Static start
		// https://github.com/sveltejs/kit/tree/master/packages/adapter-static
		adapter: adapter({
			// default options are shown
			pages: 'build',
			assets: 'build'
			// fallback: null,
			// precompress: false
		}),
		prerender: {
			// This can be false if you're using a fallback (i.e. SPA mode)
			default: true
		},
		// Adapter Static end
		vite: {
			server: {
				host: '0.0.0.0',
				port: 3000,
				https: {
					key: readFileSync('/shared/httpd/devilbox/ca/certs/mass/skit.loc.key'),

					cert: readFileSync('/shared/httpd/devilbox/ca/certs/mass/skit.loc.crt')
				},
			},
			define: {
				// env-cmd https://blog.hdks.org/Environment-Variables-in-SvelteKit-and-Vercel/
				'process.env': process.env
			}
		}
	}
};

export default config;

With this config and npm run dev the app works under https://skit.loc:3000 without endless reload, HMR works fine.

If a .devilbox folder with nginx.yml is included in the root of the project going to https://skit.loc returns a 502 Bad Gateway from nginx.

If no .devilbox folder is in the root of the project going to https://skit.loc returns a 404 Not Found from nginx.

Using npm run dev -- --https --host 0.0.0.0 creates an on the go cert for example.org and will not be accepted for the local domain.

Having any of the options for HMR does not change anything under https://skit.loc however under https://skit.loc:3000/ these options lead to the known endless reloading issue.

				hmr: {
					host: 'skit.loc'
					protocol: 'wss',
					port: 24678
				}

nginx.yml

---
# Nginx Reverse Proxy Template defintion for vhost-gen.py
#
# The 'feature' section contains optional features that can be enabled via
# conf.yml and will then be replaced into the main vhost ('structure' section)
# into their corresponding position:
#
#    __XDOMAIN_REQ__
#    __ALIASES__
#    __DENIES__
#    __STATUS__
#
# The features itself also contain variables to be adjusted in conf.yml
# and will then be replaced in their corresponding feature section
# before being replaced into the vhost section (if enabled):
#
# XDomain:
#    __REGEX__
# Alias:
#    __REGEX__
#    __PATH__
# Deny:
#    __REGEX__
# Status:
#    __REGEX__
#
# Variables to be replaced directly in the vhost configuration can also be set
# in conf.yml and include:
#    __VHOST_NAME__
#    __DOCUMENT_ROOT__
#    __INDEX__
#    __ACCESS_LOG__
#    __ERROR_LOG__
#

###
### Basic vHost skeleton
###
vhost: |
    server {
        listen       __PORT____HTTP_PROTO____DEFAULT_VHOST__;
        server_name  __VHOST_NAME__;

        access_log   "__ACCESS_LOG__" combined;
        error_log    "__ERROR_LOG__" warn;

        # Reverse Proxy definition (Ensure to adjust the port, currently '3000')
        location / {
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_pass http://php:3000;
        }

    __REDIRECT__
    __SSL__
    __ALIASES__
    __DENIES__
    __SERVER_STATUS__
        # Custom directives
    __CUSTOM__
    }

###
### vHost Type (normal or reverse proxy)
###
vhost_type:
    docroot: ''
    rproxy: ''

###
### Optional features to be enabled in vHost
###
features:
    # SSL Configuration
    ssl: |
        ssl_certificate           __SSL_PATH_CRT__;
        ssl_certificate_key       __SSL_PATH_KEY__;
        ssl_protocols             __SSL_PROTOCOLS__;
        ssl_prefer_server_ciphers __SSL_HONOR_CIPHER_ORDER__;
        ssl_ciphers               __SSL_CIPHERS__;

    # Redirect to SSL directive
    redirect: |
        return 301 https://__VHOST_NAME__:__SSL_PORT__$request_uri;

    # PHP-FPM left empty, as we are an reverse proxy configuration
    php_fpm: ''

    alias: |
        # Alias Definition
        location ~ __ALIAS__ {
            root  __PATH__;
        __XDOMAIN_REQ__
        }

    deny: |
        # Deny Definition
        location ~ __REGEX__ {
            deny all;
        }

    server_status: |
        # Status Page
        location ~ __REGEX__ {
            stub_status on;
            access_log off;
        }

    xdomain_request: |
        # Allow cross domain request from these hosts
        if ( $http_origin ~* (__REGEX__) ) {
            add_header "Access-Control-Allow-Origin" "$http_origin";
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
            add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
            add_header 'Access-Control-Max-Age' 0;
            return 200;
        }

Not sure what to do to have the app running under https://skit.loc without adding the :3000 port to the URL.

@robots4life robots4life reopened this Apr 8, 2022
@cytopia
Copy link
Owner

cytopia commented Apr 8, 2022

This integration test generates a working reverse proxy (via http/https without the additional port). You can generate it and compare it against your example:

https://github.com/cytopia/devilbox/blob/master/.tests/tests/rproxy-javascript.sh

@robots4life
Copy link
Author

robots4life commented Apr 9, 2022

I have tried everything, I think (and surely spent much time on this). Only works with HMR over https://devilskit.loc:3000. Fork this https://github.com/robots4life/devilskit and see yourself. Do a simple npm i and then npm run dev, would be curious to see if you can get it to work on https://devilskit.loc.

1270.0.0.1 devilskit.loc is in hosts file.

With https://github.com/robots4life/devilskit/blob/master/.devilbox/override/docker-compose.override.yml in root of Devilbox installation directory it gets even worse and reloads ``https://devilskit.loc` instantly.

Not having a docker-compose.override.yml in place it waits longer till it reloads.

Also interestingly enough when the https option is specified with links to the certs in the repo it will lead to a 502 no matter what settings are given.

See the various options in svelte.config.js in this section. Tried all possible combinations of these settings..

		vite: {
			server: {
				host: '0.0.0.0',
				// host: 'skit.loc',
				// port: 3000,				
				// https: {
				// 	key: readFileSync('./certs/devilskit.loc.key'), // leads to 502 immediately
				// 	cert: readFileSync('./certs/devilskit.loc.crt')
				// },
				hmr: {
					// host: 'skit.loc',
					host: '0.0.0.0',
					// protocol: 'wss',
					port: 24678
				}
			},

I have gone over these options https://vitejs.dev/config/#server-host many times as well, perhaps I have missed some, bottom line, for now I am working in http://localhost:3000. Would be too cool to at least know what the issue is that causes the endless reload with the Devilbox stack.

https://github.com/sveltejs/kit/issues/1134#issuecomment-964321953 does work on https://myapp.tld, though that is a custom Docker setup using port 80 and with Devilbox that is always taken.

And yes, between each change of any of the Devilbox files I did a full docker-compose down, docker-compose rm -f and docker-compose up -d. And followed https://devilbox.readthedocs.io/en/latest/reverse-proxy/reverse-proxy-with-https.html#reverse-proxy-with-https-1 as well as https://devilbox.readthedocs.io/en/latest/examples/setup-reverse-proxy-nodejs.html.

@robots4life
Copy link
Author

The Vite and SvelteKit crew have closed the issue on their end https://github.com/sveltejs/kit/issues/1134 so unless we find out what is causing the endless reload with the Devilbox I will have to use http://localhost:3000. @boumanb and @cytopia if you are interested to solve this https://github.com/robots4life/devilskit will show the issue. I keep having hope that this can be achieved with Devilbox somehow, would be very nice to be able to get a SvelteKit app going on https://app.loc with HMR. 🤞

@cytopia
Copy link
Owner

cytopia commented Apr 11, 2022

@robots4life do you want to document all the steps you've taken and the current open tasks in the wiki of this repository? Once this issue will be closed, all that information will most likely be lost (except if you dig deep into closed issues).

I can then give it a shot and will amend any findings I might discover

@robots4life
Copy link
Author

@cytopia I assume you refer to https://github.com/robots4life/devilskit when asking about documenting all the steps trying to get SvelteKit running on https://app.loc with HMR, yeah I can do that on the repo for sure and leave it public for reference.

Also happy, if we can get it running, to write documentation for Devilbox i.e. under https://devilbox.readthedocs.io/en/latest/examples/sveltekit with the steps needed.

Though not sure what repo and what you refer to with the current open tasks in the wiki of this repository. Could you clarify this ?

@cytopia
Copy link
Owner

cytopia commented Apr 11, 2022

Also happy, if we can get it running, to write documentation for Devilbox i.e. under https://devilbox.readthedocs.io/en/latest/examples/sveltekit with the steps needed.

I was refering to the wiki page of the Devilbox's GitHub repository, as I don't know how familiar people are with sphinx documentation for https://devilbox.readthedocs.io.

So my idea was using this: https://github.com/cytopia/devilbox/wiki which might motivate more people to add some examples of what they've accomplished with the Devilbox setup. Popular topics can then be moved to the official documentation once they're solid.

@robots4life
Copy link
Author

Yeah I can do that. Bottom line, I am happy to document this in any place you see fit so that other people can refer to it and get things running fine.

I will start with documenting the steps in the https://github.com/robots4life/devilskit/blob/master/README.md, or at least write down there what I have tried with the results.

@cytopia
Copy link
Owner

cytopia commented Apr 15, 2022

@robots4life I just gave it a shot and it works without any problems via correct URL and https support. It is actually quite simple. So here's what I did:

This is the relevant configuration from my .env file

DEVILBOX_PATH=.
LOCAL_LISTEN_ADDR=
TLD_SUFFIX=loc

PHP_SERVER=8.1
HTTPD_SERVER=nginx-stable

HOST_PATH_HTTPD_DATADIR=./data/www
HOST_PORT_HTTPD=80
HOST_PORT_HTTPD_SSL=443

HTTPD_DOCROOT_DIR=htdocs
HTTPD_TEMPLATE_DIR=.devilbox

1. Inside the PHP container

# Create project
mkdir /shared/httpd/svelte

# Create vhost dir and vhost-gen override dir
mkdir /shared/httpd/svelte/htdocs
mkdir /shared/httpd/svelte/.devilbox

2. From the host system

# Copy vhost-gen template
cd /path/to/devilbox/repository
cp cfg/vhost-gen/nginx.yml-example-rproxy data/www/svelte/.devilbox/nginx.yml

3. Change port on vhost-gen template (from host system)

cd /path/to/devilbox/repository
vim data/www/svelte/.devilbox/nginx.yml
-        proxy_pass http://php:8000;
+        proxy_pass http://php:3000;

4. Inside the PHP container

# Ensure custom vhost config is picked up by renaming dir
cd /shared/httpd/
mv svelte svelte.bak
# Wait 2-3 seconds
mv svelte.bak svelte

# Create svelte project
cd /shared/httpd/svelte
npm init svelte@next my-app
cd my-app
npm install

# Start svelte
npm run dev -- --host 0.0.0.0

Now you can go to https://svelte.loc/ with your browser and it works fine

Screenshot 2022-04-15 11-14-14  selection

It then also shows fine on the vhost page in the Devilbox intranet

Screenshot 2022-04-15 11-21-01  selection

Further automation

If you want the dev server to startup automatically every time the Devilbox starts, you can integrate it into pm2. The relevant documentation can be found here:

@cytopia cytopia added documentation and removed bug labels Apr 15, 2022
@cytopia cytopia self-assigned this Apr 15, 2022
@robots4life
Copy link
Author

Thank you for giving this a shot and obviously getting it to work. 🎉
Unfortunately there are several steps I did different based on the Devilbox docs I found. I must have either misunderstood or not understood several points in the docs since what I tried did not work. Like I said I will document this repo https://github.com/robots4life/devilskit and the steps I took based on the Devilbox docs and then we can see and compare why and what I have done differs from what you managed and either make the Devilbox docs more detailed or leave them as is if I have not followed them correctly.
For sure I am also very happy to write further documentation for Devilbox wherever I can.

@robots4life
Copy link
Author

robots4life commented Apr 16, 2022

I have started writing the documentation.

Unfortunately bad news, I replicated how you got things to work exactly and face the endless reloading issue or rather HMR not working and not connecting.

Can you do me a favor please and once you start the SvelteKit app on https://svelte.loc can you open Dev Tools in the browser and check the Console for a log entry saying "[vite] connected." by the file client.ts.53:14 ?

Do you have that in your console log ? When I follow what you did it never connects to the Vite HRM server and hangs at [vite] connecting....

Also with how you did things, when you go into /shared/httpd/svelte/my-app and edit src/routes/index.svelte and just add an <h1>Test</h1> at the bottom of the file and save the file the change should be visible immediately in the app in the browser, that does not work.

To keep things simple just opt for the Skeleton when you install the SvelteKit app, though regardless of what install option you choose the changes to the files should immediately be reflected by Vite's HMR.

While you have the app running try going to http://localhost:3000/ to see how HMR connects and how changes to the code are reflected in the browser immediately. Also if you try https://svelte.loc:3000 it should work with HMR connecting.

@cytopia
Copy link
Owner

cytopia commented Apr 17, 2022

http://svelte.loc/

In the console I also only get:

Error with Permissions-Policy header: Unrecognized feature: 'interest-cohort'.
[vite] connecting...

And then:

client.ts:22 WebSocket connection to 'ws://svelte.loc/' failed: 
(anonymous) @ client:188
client.ts:219 [vite] server connection lost. polling for restart...

Adding custom HTML in src/routes/index.svelte works however

Screenshot 2022-04-17 10-08-43  selection

http://svelte.loc/__vite_ping

When visiting the ping URL in a new tab I get a successful result

pong

@robots4life
Copy link
Author

HMR over wss needs to connect and work. Check out the video.

HMR makes the changes available without a browser reload, i.e. form values are kept while one works on a form etc.

Error OK
http://localhost:3000 X
https://devilskit.loc X
https://devilskit.loc/__vite_ping X
https://devilskit.loc:3000 X
https://devilskit.loc:3000/__vite_ping X

@cytopia
Copy link
Owner

cytopia commented Apr 17, 2022

The I think it has issues reaching it through the reverse proxy. Are there any examples on how to set this up properly with an Nginx reverse proxy?

@robots4life
Copy link
Author

robots4life commented Apr 18, 2022

This seems to be an example that should work, I have not tried it but will give this a go to check if things can be made to work with Vite and a Docker environment.
sveltejs/kit#1134 (comment)
I am not the most familiar with Docker, perhaps you could give this a run as well and report back so we can rule out Vite not working and the error being on the Docker side.

I have a feeling though that it could be made to work with specific vite.server.hmr settings, however so far I have not found the right mix. This post suggests using a different port for HMR. vitejs/vite#3578

I have also found vitejs/vite#4259 (comment) and vitejs/vite#3093 as well. Not sure what is going on with the websocket connection and how to set it up correctly.

@cytopia
Copy link
Owner

cytopia commented Apr 18, 2022

For me the endless reloading stopped by:

  1. Using https in the browser instead of http
  2. Using nginx-mainline instead of nginx-stable

With the following server directive in the vhost-gen yaml file:

  server {
      listen       __PORT____HTTP_PROTO____DEFAULT_VHOST__;
      server_name  __VHOST_NAME__;

      access_log   "__ACCESS_LOG__" combined;
      error_log    "__ERROR_LOG__" warn;

      # Reverse Proxy definition (Ensure to adjust the port, currently '8000')
      location / {

        # redirect all HTTP traffic to localhost:3000
        proxy_pass          http://php:3000;
        proxy_set_header    Host                $host;
        proxy_set_header    X-Real-IP           $remote_addr;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;

        proxy_read_timeout 86400;

        # WebSocket support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
      }

  __REDIRECT__
  __SSL__
  __ALIASES__
  __DENIES__
  __SERVER_STATUS__
      # Custom directives
  __CUSTOM__
  }

And the following svelte.config.js

import adapter from '@sveltejs/adapter-auto';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  kit: {
    vite: {
      server: {
        host: '0.0.0.0',
        port: 3000,
        strictPort: true,
        hmr: {
          clientPort: 443
        }
      }
    },
    adapter: adapter(),

    // Override http methods in the Todo forms
    methodOverride: {
      allowed: ['PATCH', 'DELETE']
    }
  }
};

export default config;

I then start it up via:

 npm run dev -- --open

@robots4life
Copy link
Author

I can confirm, it works on https://devilskit.loc with your changes to the vhost-gen yaml file and the config for the Vite server with HMR. Thank you for having a look into this and coming up with a working setup. 🤞 🎉 💯 😎

I will document how to get it to work in the repo and I would love to contribute to your docs on how to get this to work as well with examples for Nginx and Apache.

If you could explain what the config settings for Vite, especially strictPort and clientPort do and how they make websockets work with Nginx I could elaborate on this in the docs. I'd love to thoroughly understand this and then make it available to all users of the Devilbox. Also why did you opt for nginx-mainline instead of nginx-stable ?

Then to be complete with the Devilbox docs and to provide example setups it would be great to have the vhost-gen yaml files for Apache 2.2 and Apache 2.4 as well.

@robots4life
Copy link
Author

@cytopia have a look at the documentation of the example setup and let me know where I can be of help writing this up for your Devilbox documentation.

If you could add websockets support to the vhost-gen templates of Apache 2.2. and Apache 2.4 I could write up a complete example. Bottom line, thank you for your help on this issue, if you need any help with doing something for Devilbox let me know, thank you.

@cytopia
Copy link
Owner

cytopia commented Apr 19, 2022

The documentation looks straigh forward 👍 For the values you asked me about, I actually don't really know what strictPort or clientPort do, I trial&errored them together until it workied, based off a couple of different google searches.

@robots4life
Copy link
Author

@cytopia https://github.com/robots4life/devilskit/issues/1

Having an issue with Nginx resolving the static build. If you have a little bit of time, it seems one has to add a Nginx conf setting, but I would not know how exactly to accomplish that, thank you.

@cytopia
Copy link
Owner

cytopia commented Jul 20, 2022

@cytopia robots4life/devilskit#1

I've replied in your thread

@cytopia
Copy link
Owner

cytopia commented Dec 26, 2022

@robots4life when trying out your demo app I get the following error upon opening the project via browser:

Failed to load PostCSS config (searchPath: /shared/httpd/devilskit): [Error] Loading PostCSS Plugin failed: Cannot find module 'tailwindcss'
Require stack:
- /shared/httpd/devilskit/postcss.config.cjs

(@/shared/httpd/devilskit/postcss.config.cjs)
Error: Loading PostCSS Plugin failed: Cannot find module 'tailwindcss'
Require stack:
- /shared/httpd/devilskit/postcss.config.cjs

@robots4life
Copy link
Author

@robots4life when trying out your demo app I get the following error upon opening the project via browser:

Failed to load PostCSS config (searchPath: /shared/httpd/devilskit): [Error] Loading PostCSS Plugin failed: Cannot find module 'tailwindcss'
Require stack:
- /shared/httpd/devilskit/postcss.config.cjs

(@/shared/httpd/devilskit/postcss.config.cjs)
Error: Loading PostCSS Plugin failed: Cannot find module 'tailwindcss'
Require stack:
- /shared/httpd/devilskit/postcss.config.cjs

On the version of Devilbox I currently use it works ok.

git clone https://github.com/robots4life/devilskit.git

npm install --verbose

touch .env

npm run dev

I can see the SvelteKit app running under i.e. https://devilskit.loc without a reloading issue or the PostCSS config loading error.

Have you tried it with running these above commands and still get the error ?

Now perhaps the error comes from using the latest version of Devilbox.
I checked my local Devilbox instance, in the CHANGELOG.md file I found this version Release v2.1.1 (2022-04-07).
What version of Devilbox are you using ?

I assume you expect me to up update my Devilbox https://devilbox.readthedocs.io/en/latest/maintenance/update-the-devilbox.html and then try running the demo app again ?

Another thing I could do is strip the demo app down to just the SvelteKit default install and the correct settings in vite.config.js. https://github.com/robots4life/devilskit/blob/master/vite.config.js#L8-#L15

Then it would be up to the user to decide if they like to use TailwindCSS with PostCSS at all and if so consult the available documentation on how to achieve this. Perhaps this is better, since users totally new to SvelteKit might otherwise believe that this is the default behavior while this is not true.

However in the demo app I also include a form and show how to receive the post data on the server, for this to work with Devilbox during development the setting https://kit.svelte.dev/docs/configuration#csrf is set to false here https://github.com/robots4life/devilskit/blob/master/svelte.config.js#L39 and has to be set to true for production. Perhaps I should also omit this example and like I said, just use the bare default SvelteKit install and leave all additional options to the user.

In essence it boils down to having these Vite settings https://github.com/robots4life/devilskit/blob/master/vite.config.js#L8-#L15 and that makes it work with Devilbox and everything else is just additional "nice to have" options.

@cytopia
Copy link
Owner

cytopia commented Dec 27, 2022

On the version of Devilbox I currently use it works ok.

git clone https://github.com/robots4life/devilskit.git

npm install --verbose

touch .env

npm run dev

This one works. I only see a demo page, so I can't judge if the functionality is correct.

Screenshot 2022-12-27 14-04-21  selection

If you switch to this version Devilbox v3.0.0-beta-0.2, then there is no need anymore for override templates. All you gotta do is add a backend.cfg config file into the .devilbox/ config dir with:

# Websocket Proxy Backend
conf:rproxy:ws:php:3000

I have also tried this one, which seemingly works as well

# HTTP Proxy Backend
conf:rproxy:http:php:3000

Screenshot 2022-12-27 14-02-49  selection

Let me know which of the above works for you (a.k.a is the correct way to setup SvelteKit)

@robots4life
Copy link
Author

robots4life commented Feb 23, 2023

https://discord.com/channels/457912077277855764/1078047640274599977/1078047640274599977

I found a super strange issue where https://kit.svelte.dev/docs/load#invalidation-manual-invalidation invalidate('page') and depends('page') will fail silently when there is no : colon in the string given as argument to these 2 functions with the above Vite config.

      server: {
        host: '0.0.0.0',
        port: 3000,
        strictPort: true,
        hmr: {
          clientPort: 443
        }

Here is an example of how it should work. https://learn.svelte.dev/tutorial/custom-dependencies

Working on localhost:5173 works fine.

Going to update to latest version of Devilbox to see if the issue persists and if so, we are back to square one with the endless reload issue, as that is what happens when I change the port to 5173 in the Vite config and in project/.devilbox/nginx.yml.

Checking with the SvelteKit team if there has to be a colon in the string passed to depends() and invalidate(), since if the colon is included it works just fine with the above Vite config.

Since any string that begins with an [a-z]+: pattern is a valid URL, we can create custom invalidation keys like data:now.

So I assume having invalidate('page') and depends('page') does not match the pattern of a valid URL.

@robots4life
Copy link
Author

@cytopia @boumanb

I have deleted and made a new devilskit repo with 3 branches. Feel free to kindly star the repository again and add it to any part of the documentation, as you like.

✅ The master branch shows how SvelteKit and HMR work with Devilbox on the default http://localhost:5173 development domain.
https://github.com/robots4life/devilskit/tree/master

✅ The secure-local-domain branch shows how SvelteKit and HMR work with Devilbox on the i.e. https://devilskit.loc secure local development domain.
https://github.com/robots4life/devilskit/tree/secure-local-domain
I can confirm, having the backend.cfg file with conf:rproxy:ws:php:3000 or conf:rproxy:http:php:3000 in it works super nice. 👌

✅ The static-build branch shows how a 100% static build of the SvelteKit project works with Devilbox on the i.e. https://static.loc preview domain.
https://github.com/robots4life/devilskit/tree/static-build

@masiorama masiorama mentioned this issue Mar 10, 2023
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants