Configuration:
Laravel Mix 6.0.16
Laravel Valet 2.13.19
webpack 5.30.0
webpack-cli 4.6.0
webpack-dev-server 4.0.0-beta.1
Description:
I try to enable https for hot replacement in Laravel 8 on MacOs with Valet. I did my site secure, add --https in my package.json
"hot": "mix watch --hot --https"
Then I launch command in CLI
yarn hot
And it was successful, but when I open my site I saw error in browser console http://joxi.ru/nAypq4ZTwJBP52
net::ERR_CERT_AUTHORITY_INVALID
I found the solution.
Remove --https from script definition in package.json
Add configuration in the file webpack.mix.js
mix.options({
hmrOptions: {
host: url,
port: 8080
}
})
mix.webpackConfig({
devServer: {
https: {
key: fs.readFileSync('/Users/alex/.config/valet/Certificates/castle.test.key'),
cert: fs.readFileSync('/Users/alex/.config/valet/Certificates/castle.test.crt')
}
}
})
In my case I got the mixed content issue. I found out the publicPath was still using http instead of https. I fixed the public path by overriding it. Also made added a few checks to read the certificates if they exist and made the certificate path generic.
const homeDir = process.env.HOME;
const host = process.env.APP_URL.split('//')[1];
const port = '8080';
mix.options({
hmrOptions: {
host,
port
}
});
if (
process.argv.includes("--hot") &&
fs.existsSync(path.resolve(homeDir, `.config/valet/Certificates/${host}.key`)) &&
fs.existsSync(path.resolve(homeDir, `.config/valet/Certificates/${host}.crt`))
) {
mix.webpackConfig({
devServer: {
https: {
key: fs.readFileSync(path.resolve(homeDir, `.config/valet/Certificates/${host}.key`)).toString(),
cert: fs.readFileSync(path.resolve(homeDir, `.config/valet/Certificates/${host}.crt`)).toString()
},
}
});
// overriding publicPath as it was using http and causing mixed-content
mix.override(c => {
c.output.publicPath = process.env.APP_URL + `:${port}/`
});
}
Update
laravel-mix-valet is available on npm which works with laravel valet
require('laravel-mix-valet');
const host = process.env.APP_URL.split('//')[1];
mix.js('resources/js/app.js', 'public/js')
.valet(host)
.vue();
This works for our team (running "hot": "mix watch --hot", without the --https):
if (!mix.inProduction() && process.env.DEV_SERVER_KEY) {
let proxy = process.env.APP_URL.replace(/^(https?:|)\/\//,'');
mix.options({
hmrOptions: {
host: proxy,
port: '8080',
https: {
key: process.env.DEV_SERVER_KEY,
cert: process.env.DEV_SERVER_CERT
}
}
});
}
Related
I'm hosting my App on an EC2-instance behind an Elastic Load Balancer which manages my SSL-Certificate. On this EC2-Instance my nginx-configuration is redirecting all http-Requests to https.
I recently switched to Vite which caused me a lot of trouble. When I push my app to the server after calling npm run build my assets are blocked. In the browser console I get:
Mixed Content: The page at 'example.com' was loaded over HTTPS, but requested an insecure ...
My Setup:
vite.config.js
export default defineConfig({
server: {
host: 'localhost',
},
plugins: [
laravel([
'resources/assets/sass/app.sass',
// etc...
]),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
});
Setting "https: true" in the server-block didn't help me.
.env
APP_ENV=production
APP_URL=https://example.com
ASSET_URL=https://example.com
In my blade template I'm using the Vite-directive:
#vite('resources/assets/sass/app.sass')
I tried the following solutions:
Setting $proxies = '*' in TrustProxies.php, which doesn't have any effect.
Setting URL::forceScheme('https'); in AppServiceProvider.php, which will load the assets but lead to a lot of other issues.
Somehow the #vite-directive is not resolving my assets as secure assets. With Laravel Mix I could just call secure_asset.
How can I fix this?
In the end I used the TrustedProxies-middleware. However back then I forgot to register it as global middleware.
import fs from 'fs';
const host = 'example.com';
server: {
host,
hmr: {host},
https: {
key: fs.readFileSync(`ssl-path`),
cert: fs.readFileSync(`ssl-cert-path`),
},
},
you should add this to vite.config.js file along with ASSET_URL to your .env file
I am using the Microsoft Vue tutorial to create a solution with separate frontend and backend projects. I am using the default configuration that enables tls and I have trusted the IIS Express Development Certificate, but the frontend project appears to use the public IP address in hmr requests which are not included in the dev certificate that is based on localhost only.
My vue.config.js is as follows:
const fs = require('fs')
const path = require('path')
const HttpsAgent = require('agentkeepalive').HttpsAgent
const baseFolder =
process.env.APPDATA !== undefined && process.env.APPDATA !== ''
? `${process.env.APPDATA}/ASP.NET/https`
: `${process.env.HOME}/.aspnet/https`
const certificateArg = process.argv.map(arg => arg.match(/--name=(?<value>.+)/i)).filter(Boolean)[0]
const certificateName = certificateArg ? certificateArg.groups.value : 'WebAppFrontend'
if (!certificateName) {
console.error('Invalid certificate name. Run this script in the context of an npm/yarn script or pass --name=<<app>> explicitly.')
process.exit(-1)
}
const certFilePath = path.join(baseFolder, `${certificateName}.pem`)
const keyFilePath = path.join(baseFolder, `${certificateName}.key`)
module.exports = {
devServer: {
// host: 'localhost',
https: {
key: fs.readFileSync(keyFilePath),
cert: fs.readFileSync(certFilePath),
},
proxy: {
'^/weatherforecast': {
target: 'https://localhost:5001/',
changeOrigin: true,
agent: new HttpsAgent({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000,
freeSocketTimeout: 90000
}),
onProxyRes: (proxyRes) => {
const key = 'www-authenticate'
proxyRes.headers[key] = proxyRes.headers[key] && proxyRes.headers[key].split(',')
}
}
},
port: 5002
}
}
I tried to manually set the webpack host option to localhost but Visual Studio cannot start the backend project. If I modify the startup projects from both the front and backend projects to just the backend and then execute npm run serve manually, everything works fine.
How do I force the SockJS calls to use localhost instead of the public IP address without breaking the Visual Studio debugging setup?
Just fix same Error. Try this
in vue.config.js
module.exports = {
devServer: {
host: '0.0.0.0',
public: '0.0.0.0:5002',
disableHostCheck: true,
I am using #vue/cli 5.0.4 in a project with webpack-dev-server#4.9.0
I tried the solution from #asp.entwickler but got some errors because disableHostCheck and public have been deprecated.
According to https://cli.vuejs.org/migrations/migrate-from-v4.html#vue-cli-service
webpack-dev-server has been updated from v3 to v4. So there are breaking changes with regard to the devServer option in vue.config.js.
The disableHostCheck option was removed in favor allowedHosts: 'all';
public, sockHost, sockPath, and sockPort options were removed in favor client.webSocketURL option.
so the solution was to set devServer.client.webSocketURL.hostname. Also setting allowedHosts: 'auto' instead of 'all' seems to be a good idea unless you really need it.
When set to 'auto' this option always allows localhost, host, and client.webSocketURL.hostname:
module.exports = {
devServer: {
allowedHosts: 'auto',
client: {
webSocketURL:
{
hostname: 'localhost'
}
},
I'm trying to bootstrap a new Nextjs app, and for integrating with Auth0 I need my localhost to be running HTTPS. I followed the guide here (https://medium.com/responsetap-engineering/nextjs-https-for-a-local-dev-server-98bb441eabd7), and generated a local certificate which is in more trusted certificate store.
To use HTTPS for localhost, you apparently need to create a custom server (this seems an odd oversight on the Nextjs side), so here's my custom server:
const { createServer } = require('https');
const { parse } = require('url');
const next = require('next');
const fs = require('fs');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev, dir: __dirname });
const handle = app.getRequestHandler();
const httpsOptions = {
key: fs.readFileSync('./certificates/ReactDevCertificate.key'),
cert: fs.readFileSync('./certificates/ReactDevCertificate.cer'),
};
app.prepare().then(() => {
createServer(httpsOptions, (req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(3000, (err) => {
if (err) throw err;
console.log('> Server started on https://localhost:3000');
});
});
Now, previous without the custom server, the app loads fine. But, with the custom server, it fails to load:
➜ yarn run dev
yarn run v1.22.15
$ next dev ./server.js
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
Error: > No `pages` directory found. Did you mean to run `next` in the parent (`../`) directory?
at Object.findPagesDir (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\lib\find-pages-dir.js:31:15)
at new DevServer (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\dev\next-dev-server.js:110:44)
at NextServer.createServer (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\next.js:102:20)
at C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\next.js:117:42
at async NextServer.prepare (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\next.js:92:24)
at async C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\cli\next-dev.js:126:9
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
It feels like somewhere the app has navigated to a child folder, as there is code in the function find-pages-dir.js (https://github.com/vercel/next.js/blob/canary/packages/next/lib/find-pages-dir.ts#L22) that looks specifically to the parent directory for the pages folder.
For reference, here is my package.json:
{
"name": "fictionist-ui",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev ./server.js",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "12.0.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^2.0.4"
},
"devDependencies": {
"#types/node": "16.11.6",
"#types/react": "17.0.33",
"eslint": "7.32.0",
"eslint-config-next": "12.0.1",
"typescript": "4.4.4"
}
}
OS: Windows 11
NPM: 16.9.0
Yarn: 1.22.15
My mistake was that I didn't get the command right:
"scripts": {
"dev": "node server.js" // was "next dev ./server.js"
}
This is for my Laravel + Vue SPA app.
I have this Laravel Mix config file here:
const path = require('path');
const fs = require('fs-extra');
const mix = require('laravel-mix');
const tailwindcss = require('tailwindcss');
require('laravel-mix-bundle-analyzer');
function publishAssets() {
const publicDir = path.resolve(__dirname, './public');
if (mix.inProduction()) {
fs.removeSync(path.join(publicDir, 'dist'));
}
fs.copySync(path.join(publicDir, 'build', 'dist'), path.join(publicDir, 'dist'));
fs.removeSync(path.join(publicDir, 'build'));
}
mix.js('resources/js/app.js', 'public/dist/js')
.sass('resources/sass/app.scss', 'public/dist/css').options({
postCss: [tailwindcss('./tailwind.config.js')],
processCssUrls: false,
});
// alias the ~/resources folder
mix.webpackConfig({
plugins: [
// new BundleAnalyzerPlugin()
],
resolve: {
extensions: ['.js', '.json', '.vue'],
alias: {
'#': `${__dirname}/resources`,
'~': path.join(__dirname, './resources/js'),
ziggy: path.join(__dirname, './vendor/tightenco/ziggy/dist/js/route.js'),
},
},
output: {
chunkFilename: 'dist/js/[chunkhash].js',
path: mix.config.hmr ? '/' : path.resolve(__dirname, './public/build'),
},
});
mix.then(() => {
if (!mix.config.hmr) {
process.nextTick(() => publishAssets());
}
});
It works fine with npm run watch, but when I do npm run production, the CSS doesn't work. The site loads and works, but the CSS is missing.
Can anyone see what in my code is causing it?
Here's my spa.blade.php:
<link rel="stylesheet" href="{{ mix('dist/css/app.css') }}">
...
<script src="{{ mix('dist/js/app.js') }}"></script>
In the network tab of Chrome dev tools, the CSS file is 270kb in develop environment and 42kb in prod environment.
Something is getting translated wrong.
In my case, it cause by setting wrong property "purge" in tailwindcss config file.
When I ran "npm run hot" or "npm run dev", the website was fine.
But it broke when I ran "npm run prod".
It seems the dev mode ignore the property "purge".
I'm calling this solved for now because my site started working.
it was extremely difficult to navigate since I had 6 months of work on a dev branch, and it worked via npm run watch. When I merged into master, npm run production loaded incorrectly--the styles were half there and half missing.
The solution was to downgrade from tailwindcss#1.9 to tailwindcss#1.4.
Along my way, I read something about postcss or something not working with the --no-progress flag which is on npm run production.
A person could try removing that flag, but I already downgraded tailwind so I didn't try that.
I have an angularJs App which I built with grunt and a server backend written in Java running on a tomcat server. To wire those together when development I wanted to use grunt-connect-proxy. But I could not get it to work even a bit.
All the "examples" and "demos" I found on the web happened to use a several hundred lines long Gruntfile.js. That turned out not to be really useful in finding my problem. What does a minimal (!) example look like?
This is how you can create a minimal demo which is just a proxy to google.com:
Run:
npm install grunt-connect-proxy --save-dev
npm install grunt-contrib-connect --save-dev
and creat the following Gruntfile.js:
module.exports = function (grunt) {
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;
grunt.initConfig({
connect: {
server: {
options: {
hostname: 'localhost',
keepalive: true,
open: true,
middleware: function (connect, options) {
return [proxySnippet];
}
},
proxies: [{
context: '/',
host: 'google.com',
port: 80
}]
}
}
});
grunt.loadNpmTasks('grunt-connect-proxy');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.registerTask('default', [
'configureProxies:server',
'connect:server']);
};
Now just run grunt.