Add redirects rule inside t3 app

Hi how can I add a redirects rule in the t3 next.config file. Currently my file looks like this:
// @ts-check

import { redirect } from "next/dist/server/api-utils/index.js";

/**
* Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation.
* This is especially useful for Docker builds.
*/
!process.env.SKIP_ENV_VALIDATION && (await import("./src/env/server.mjs"));

/**
* Don't be scared of the generics here.
* All they do is to give us autocompletion when using this.
* @template {import('next').NextConfig} T
* @constraint {{import('next').NextConfig}}
* @param {{reactStrictMode?: boolean;swcMinify?: boolean;output?: string;images?: {domains: string[];};i18n?: {locales: string[];defaultLocale: string;};webpack?: any;}} nextConfig
*/
function defineNextConfig(nextConfig) {
const webpack = nextConfig.webpack
nextConfig.webpack = (
/** @type {{ module: { rules: { test: RegExp; issuer: RegExp; use: string[]; }[]; }; }} */
config,
/** @type {any} */
options) => {
config.module.rules.push({
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: ['@svgr/webpack'],
})
// Preserve custom webpack config
return typeof webpack === "function" ? webpack(config, options) : config
};
return nextConfig;
}

export default defineNextConfig({
reactStrictMode: true,
swcMinify: true,
output: "standalone",
images: {
domains: ['cdn.discordapp.com'],
},
i18n: {
locales: ["en"],
defaultLocale: "en",
},
});
// @ts-check

import { redirect } from "next/dist/server/api-utils/index.js";

/**
* Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation.
* This is especially useful for Docker builds.
*/
!process.env.SKIP_ENV_VALIDATION && (await import("./src/env/server.mjs"));

/**
* Don't be scared of the generics here.
* All they do is to give us autocompletion when using this.
* @template {import('next').NextConfig} T
* @constraint {{import('next').NextConfig}}
* @param {{reactStrictMode?: boolean;swcMinify?: boolean;output?: string;images?: {domains: string[];};i18n?: {locales: string[];defaultLocale: string;};webpack?: any;}} nextConfig
*/
function defineNextConfig(nextConfig) {
const webpack = nextConfig.webpack
nextConfig.webpack = (
/** @type {{ module: { rules: { test: RegExp; issuer: RegExp; use: string[]; }[]; }; }} */
config,
/** @type {any} */
options) => {
config.module.rules.push({
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: ['@svgr/webpack'],
})
// Preserve custom webpack config
return typeof webpack === "function" ? webpack(config, options) : config
};
return nextConfig;
}

export default defineNextConfig({
reactStrictMode: true,
swcMinify: true,
output: "standalone",
images: {
domains: ['cdn.discordapp.com'],
},
i18n: {
locales: ["en"],
defaultLocale: "en",
},
});
Kind of confused where and how to set the redirects rule, basically in my case I want to redirect to sign-in if the user is not signed-in, else he should be redirected to /dashboard
9 Replies
dingo
dingo2y ago
I think what you are looking for is NextJS Middleware. Take a look at the docs here: https://nextjs.org/docs/advanced-features/middleware
Advanced Features: Middleware | Next.js
Learn how to use Middleware to run code before a request is completed.
fotoflo
fotoflo2y ago
So if you want normal 301 (or 302) redirects, you add it to your next config
const config = {
reactStrictMode: true,
swcMinify: true,
...
async redirects() {
return [
{
source: "/dashboard",
destination: "/dashboard/pages", // Matched parameters can be used in the destination
permanent: true,
},
];
},
};
export default config;
const config = {
reactStrictMode: true,
swcMinify: true,
...
async redirects() {
return [
{
source: "/dashboard",
destination: "/dashboard/pages", // Matched parameters can be used in the destination
permanent: true,
},
];
},
};
export default config;
if you want to do it based on session you can do it elsewhere Serverside Session Handler:
import type { GetServerSidePropsContext } from "next";
import { authOptions } from "src/pages/api/auth/[...nextauth]";
import { unstable_getServerSession } from "next-auth";

// log the user in if they have a session, and pass through any params

const ServerSideSessionHandler = async (
context: GetServerSidePropsContext,
params?: object
) => {
const session = await unstable_getServerSession(
context.req,
context.res,
authOptions
);

if (!session && context.resolvedUrl.match("/dashboard")) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}

return {
props: {
session,
...params,
},
};
};

export default ServerSideSessionHandler;
import type { GetServerSidePropsContext } from "next";
import { authOptions } from "src/pages/api/auth/[...nextauth]";
import { unstable_getServerSession } from "next-auth";

// log the user in if they have a session, and pass through any params

const ServerSideSessionHandler = async (
context: GetServerSidePropsContext,
params?: object
) => {
const session = await unstable_getServerSession(
context.req,
context.res,
authOptions
);

if (!session && context.resolvedUrl.match("/dashboard")) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}

return {
props: {
session,
...params,
},
};
};

export default ServerSideSessionHandler;
index.tsx
export async function getServerSideProps(context: GetServerSidePropsContext) {
// pass through the CSFR token, this is useful to build the login form
// https://next-auth.js.org/configuration/pages

const csrfToken = await getCsrfToken(context);
return ServerSideSessionHandler(context, { csrfToken });
}
export async function getServerSideProps(context: GetServerSidePropsContext) {
// pass through the CSFR token, this is useful to build the login form
// https://next-auth.js.org/configuration/pages

const csrfToken = await getCsrfToken(context);
return ServerSideSessionHandler(context, { csrfToken });
}
@dinozoidyt - is this not the best way to do it?
utdev
utdevOP2y ago
@fotoflo this works in the config but getting a type error:
export default defineNextConfig({
reactStrictMode: true,
swcMinify: true,
output: "standalone",
images: {
domains: ['cdn.discordapp.com'],
},
i18n: {
locales: ["en"],
defaultLocale: "en",
},
async redirects() {
return [
{
source: "/",
destination: "/sign-in", // Matched parameters can be used in the destination
permanent: true,
},
];
},
});
export default defineNextConfig({
reactStrictMode: true,
swcMinify: true,
output: "standalone",
images: {
domains: ['cdn.discordapp.com'],
},
i18n: {
locales: ["en"],
defaultLocale: "en",
},
async redirects() {
return [
{
source: "/",
destination: "/sign-in", // Matched parameters can be used in the destination
permanent: true,
},
];
},
});
error
Argument of type '{ reactStrictMode: true; swcMinify: true; output: string; images: { domains: string[]; }; i18n: { locales: string[]; defaultLocale: string; }; redirects(): Promise<{ source: string; destination: string; permanent: boolean; }[]>; }' is not assignable to parameter of type '{ reactStrictMode?: boolean | undefined; swcMinify?: boolean | undefined; output?: string | undefined; images?: { domains: string[]; } | undefined; i18n?: { locales: string[]; defaultLocale: string; } | undefined; webpack?: any; }'.
Object literal may only specify known properties, and 'redirects' does not exist in type '{ reactStrictMode?: boolean | undefined; swcMinify?: boolean | undefined; output?: string | undefined; images?: { domains: string[]; } | undefined; i18n?: { locales: string[]; defaultLocale: string; } | undefined; webpack?: any; }'.ts(2345)
Argument of type '{ reactStrictMode: true; swcMinify: true; output: string; images: { domains: string[]; }; i18n: { locales: string[]; defaultLocale: string; }; redirects(): Promise<{ source: string; destination: string; permanent: boolean; }[]>; }' is not assignable to parameter of type '{ reactStrictMode?: boolean | undefined; swcMinify?: boolean | undefined; output?: string | undefined; images?: { domains: string[]; } | undefined; i18n?: { locales: string[]; defaultLocale: string; } | undefined; webpack?: any; }'.
Object literal may only specify known properties, and 'redirects' does not exist in type '{ reactStrictMode?: boolean | undefined; swcMinify?: boolean | undefined; output?: string | undefined; images?: { domains: string[]; } | undefined; i18n?: { locales: string[]; defaultLocale: string; } | undefined; webpack?: any; }'.ts(2345)
fotoflo
fotoflo2y ago
i think there's somewhere in t3app where they define the types for the config file
Yiannis
Yiannis2y ago
i did mine like this but i dunno how secure it is. Did it like that incase i ever need static pages that wont be server generated:
Yiannis
Yiannis2y ago
this is in the middleware.ts file the matcher sets in which routes this will run on
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Yiannis
Yiannis2y ago
oh wow that makes a lot of sense ! What i did probably wasn't too secure anyways... Should probably get around finishing reading those docs
utdev
utdevOP2y ago
@arcanist Would you create like a protected which which contains that logic on unauth? Let me try that out looks promising
Want results from more Discord servers?
Add your server