NextJs redirect based on Regex - reactjs

I am using Next.js and I am trying to redirect to a given path base on some regex conditions and cookie.
The goal is to redirect to /foo/bar when the source does not have the key bar and have a given cookie.
I have tried several different ways with next.config.js and none works.
Right now I have the following
async redirects() {
return [
{
source: '/(^(?:(?!bar).)*$)',
has: [{
type: 'cookie',
key: 'utm_source',
value: 'bar',
}],
destination: '/foo/bar',
permanent: true
}
]
}
The documentation is quite vague.

I also had a regex issue and was digging deep into next.js source code and did a little debugging. What I found is that unfortunately nobody tells you that next.js wraps your regex inside /^(?:\/( your regex ))$/i
Actually, the first part (\/) might depend on your source property.
But if you remove everything apart from the actual "word regex" it should work:
source: '/(?!bar)',
(Check out regexp.source in getPathMatch() in node_modules\next\dist\shared\lib\router\utils\path-match.js)

Related

Backstage - How to consume environment variables?

The Backstage documentation states that all environment variables must be "exposed" through the central configuration file, app-config.yaml.
However, the official documentation is not clear about the use of these variables, for example, in the .ts and .tsx files.
Could someone help, or exemplify with codes how this use is made?
Had the same question, ended up just using process.env.ENV_VAR in the typescript files and exporting environment variables before starting Backstage.
There's a standard configuration API for both frontend and backend plugins or codes. An API reference can be found here.
You can try something like:
import { Config } from '#backstage/config';
interface IBackendConfig {
KEY_1: string;
KEY_2: string;
KEY_3: string;
}
const getBackendConfig = (config: Config): IBackendConfig => {
return config.get<IBackendConfig>('backend.env');
}
In your app-config.yaml
backend:
env:
KEY_1: "value1"
KEY_2: "value2"
KEY_3: "value3"
Note: Because of this syntax, configuration keys cannot contain dots.
Another option for accessing the env value is to create a sub-view of the configuration,
config.getConfig('backend').getString('env').

Is there a way to rename automatically generated routes JSON file in Next.js?

I have a problem, when I click to go to the /analytics page on my site, adblockers block the analytics.json file that's being requested by Next.js as they think it's an analytics tracker (it's not, it's a page listing analytics products).
Is there a way to rename the route files Next.js uses when navigating to server-side rendered pages on the client-side?
I want to either obfuscate the names so they're not machine readable, or have a way to rename them all.
Any help appreciated.
With thanks to #gaston-flores I've managed to get something working.
In my instance /analytics is a dynamic page for a category, so I moved my pages/[category]/index.tsx file to pages/[category]/category.tsx and added the following rewrite:
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: "/:category",
destination: "/:category/category",
},
];
},
};
This now gets the category.json file rather than analytics.json, which passes the adblockers checks and renders as expected.
Note that due to having a dynamic file name in the pages/[category] directory (pages/[category]/[product].tsx), I had to move that to pages/[category]/product/[product].tsx as I was seeing the /analytics page redirected to /analytics/category for some reason without this tweak.

Setting slash commands in discordjs v14, without builders

I've set slash commands using client.application.commands.set, and that works fine, but I'm unsure how to add permissions for these commands. I've tried several answers on stackoverflow, but I believe v14 changed how to do this, but the docs haven't been updated and use separate libraries anyways.
Here's my code, simplified.
export default async function(client) {
let commands = [
{
name: `start`,
description: `start`,
},
{
name: `stop`,
description: `stop`,
},
]
await client.application.commands.set(commands, process.env.GUILD);
}
My end goal is a script that sets process.env.GUILD scoped slash commands that are whitelisted to be used by one role.
Try checking out the discord.js.org docs on it here :) It looks like you want to use the defaultMemberPermissions, which takes a PermissionResolvable, or integer bit field. You could do something like so:
const { PermissionFlagsBits } = require('discord-api-types/v10');
// Then you could access to bit flags like so:
console.log(PermissionFlagsBits.ManageChannels);

How to change the url of gatsby sitemap?

I used https://www.gatsbyjs.com/plugins/gatsby-plugin-sitemap/ to create the sitemap for my website.
Currently, the sitemap is listed at https://www.myWebsite.com/sitemap/sitemap-0.xml, but I want it to be located at https://www.myWebsite.com/sitemap.xml
How can I change the sitemap's location? Sorry if this is obvious
You can't automatically since there's no option nor configuration to do so. Your only change is using any small Node script that changes the filename or doing it manually.
However, there's no SEO problem at all having a sitemap-0.xml as long as you point your Google's Search Console to that file.
Another solution is using gatsby-plugin-advanced-sitemap which by default outputs a file named sitemal.xml as you can see in their example: https://gatsby.ghost.org/sitemap.xml. This plugin is based on the one you are using so it should be quite straightforward swapping between them.
Another solution is to use the same gatsby-plugin-sitemap plugin and then add:
gatsby-plugin-robots-txt plugin and point to the file name in the gatsby-config Something as bellow:
{
resolve: 'gatsby-plugin-robots-txt',
options: {
host: SiteConfig.url,
sitemap: ${SiteConfig.url}/sitemap.xml, HERE PLACE sitemap-0.xml
policy: [{ userAgent: '*', allow: '/' }]
}
},
After doing that, look for set up on webpage/robots.txt to see where is the point

Hiding secret key in webpack bundle.js from redux-persist-transform-encrypt

I am using redux-persist in combination with redux-persist-transform-encrypt to encrypt my redux store in localstorage. So I implemented the encryption like so:
const encryptor = createEncryptor({
secretKey: 'my-super-secret-key',
onError: function(error) {
// Handle the error.
console.log(error);
}
});
const persistConfig: PersistConfig = {
key: 'citizentracker',
storage: storage,
blacklist: new Array('form'),
transforms: [encryptor]
};
Everything works well and the redux store is encrypted in local storage. The issue I noticed is that when I do my production bundle via webpack 4. In the bundle.js file you can see the key value by searching for "secretKey". When I did I was able to see this:
{secretKey:"my-super-secret-key",onError:function(e){console.log(e)}}
Does anybody know of a way to generate a key to use for encryption, but also hide that key from people viewing the bundle.js in sources? Or some other way of making this encryption more secure.
So one thing I went and explored the option of doing was to use uglifyjs-webpack-plugin to use with webpack. This allowed me to do object property name minification via the mangle property of the UglifyJsPlugin. So in the following code, I told it to minify only the object property of "secretKey" via regex. The secret in plain text will still exist in the bundle.js file, but at least now it will be harder to find. Still exploring additional options.
This is the new webpack plugin added to the optimization property of the webpack config variable.
optimization: {
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
mangle: {
properties: {
regex: /secretKey/
}
}
}
})
]
},
So the output into bundle.js would become:
{u:"my-super-secret-key",onError:function(e){console.log(e)}}
This helps but of course would like to hear better solutions!

Resources