Designing a Database-Driven Portfolio: Schemas, Slugs, and Content Modeling
A developer portfolio often starts as a small collection of pages: an introduction, a few projects, and a contact section. At that stage, writing the content directly into React components or Markdown files can be perfectly reasonable. The architecture becomes more complicated when the portfolio grows into a publication containing projects, technical articles, categories, tags, publication dates, search previews, and independently editable content. The challenge is no longer simply displaying information. It is representing that information consistently, retrieving it efficiently, and changing its structure without breaking existing pages.
// TABLE OF CONTENTS+
A developer portfolio often starts as a small collection of pages: an introduction, a few projects, and a contact section. At that stage, writing the content directly into React components or Markdown files can be perfectly reasonable. The architecture becomes more complicated when the portfolio grows into a publication containing projects, technical articles, categories, tags, publication dates, search previews, and independently editable content. The challenge is no longer simply displaying information. It is representing that information consistently, retrieving it efficiently, and changing its structure without breaking existing pages.
A database-driven portfolio separates content from the application code that presents it. PostgreSQL can store projects, articles, categories, URL slugs, publication states, and metadata in a structured format. A Next.js application can retrieve those records and render them as project pages, article pages, archive listings, and related-content sections. This separation makes content easier to maintain, but it also introduces responsibilities: schema design, validation, relational integrity, database migrations, and query performance.
The central design principle is straightforward: model the information according to its meaning and relationships, not according to how a particular page happens to look. A project card and a project detail page may display different fields, but both should refer to the same project record. An article appearing in a category archive should not need a second, independently maintained copy of its title and URL. A well-designed schema establishes a reliable source of truth while allowing the presentation layer to change independently.
Why a Portfolio Needs a Content Model
A content model defines the types of information an application stores, the properties each type has, and the relationships between those types. In a developer portfolio, the main content types might include projects, articles, categories, and tags. A project could have a title, description, repository URL, technology list, featured image, and publication status. An article could have a title, slug, body, summary, author, category assignments, and SEO metadata.
Without a deliberate model, these fields tend to emerge wherever they are convenient. One React component might contain a project title, another might repeat it in a homepage array, and a third might hardcode the same destination URL. Editing the title then requires locating every copy. Eventually, different pages can display inconsistent descriptions or point to outdated destinations. A centralized content model reduces this duplication by storing the underlying information once and letting multiple views consume it.
- Projects: Technical work, descriptions, technology choices, repository links, demos, and project status.
- Articles: Long-form content, summaries, publication dates, and reading information.
- Categories: Broad subjects used to organize related articles or projects.
- Tags: More specific concepts that can connect content across categories.
- Media assets: Images, diagrams, thumbnails, and their associated alternative text.
- SEO metadata: Search titles, descriptions, canonical URL overrides, and social-sharing information.
These entities do not all need separate database tables immediately. A short description is naturally a column on a project or article. A category that has its own name, slug, and description is a strong candidate for a separate table. A complex block-based article body may require a structured representation of its own. The right design depends on which information is independently managed, reused, queried, and constrained.
Identify the Content Entities and Relationships
Before writing SQL, describe the requirements in ordinary language. For example: each project has one stable identifier and one URL slug; each article has a draft or published state; a category can contain many articles; an article may belong to multiple categories; and tags can connect articles that discuss similar technologies. These statements establish the rules the database must enforce.
Relationships matter because they determine how records are connected. A one-to-many relationship exists when one category owns multiple articles and each article has at most one primary category. A many-to-many relationship exists when an article can belong to multiple categories and each category can contain multiple articles. A separate junction table represents the latter relationship in a relational database.
A practical distinction is whether the relationship itself needs attributes. Suppose an article can have several categories, but one category should be designated as its primary category. The junction table can store a Boolean field such as is_primary, alongside the two foreign keys. If the primary category must be unique per article, that requirement needs an appropriate constraint or a different modeling decision. Merely creating a many-to-many relationship does not automatically enforce every business rule associated with it.
Design the PostgreSQL Schema
PostgreSQL tables should reflect the core domain while enforcing basic rules as close to the data as possible. Each record needs a stable primary key. Human-readable slugs should be treated as public identifiers for routing, but they should not normally replace internal primary keys. A title can change, a slug can be corrected, and a record can be moved between categories without requiring every internal relationship to change.
CREATE TABLE projects (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
slug text NOT NULL UNIQUE,
summary text NOT NULL,
description text,
repository_url text,
demo_url text,
status text NOT NULL DEFAULT 'draft'
CHECK (status IN ('draft', 'published', 'archived')),
published_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
slug text NOT NULL UNIQUE,
excerpt text NOT NULL,
body jsonb NOT NULL DEFAULT '[]'::jsonb,
status text NOT NULL DEFAULT 'draft'
CHECK (status IN ('draft', 'published', 'archived')),
published_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE categories (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
slug text NOT NULL UNIQUE,
description text,
created_at timestamptz NOT NULL DEFAULT now()
);The example uses identity columns for numeric primary keys, NOT NULL for required values, UNIQUE for slugs, and CHECK constraints for allowed publication states. These are database-level rules: they remain effective regardless of whether a record is inserted through an administrative interface, a script, or another application. The body column uses JSONB because a block-based editor may need to preserve structured content rather than flattening everything into one string.
JSONB is a design choice, not an automatic requirement. It is useful when an article body consists of heterogeneous blocks such as paragraphs, headings, code samples, images, and callouts. The application should validate each block's shape before storing it. If individual blocks need independent editing, auditing, querying, or frequent reordering, a separate article_blocks table may be more appropriate. Storing structured content as JSONB does not mean PostgreSQL will automatically understand or validate the editor's complete content schema.
Choosing IDs, Types, and Constraints
A primary key identifies a row independently of its visible content. Numeric identity columns are compact and convenient for many applications. UUIDs can be useful when identifiers must be generated across independent systems or before a database insert, but they add complexity and are not inherently superior. Choose a key strategy based on the system's requirements rather than assuming that a newer identifier format guarantees better architecture.
Column types should also match their intended meaning. Use timestamptz for publication and modification timestamps when the application must represent a real point in time across time zones. Use Boolean values for true-or-false properties, numeric types for numeric quantities, and foreign keys for relationships. Avoid storing dates, identifiers, or publication states as arbitrary text when the database can represent them more precisely.
ALTER TABLE articles
ADD CONSTRAINT published_articles_need_timestamp
CHECK (
status <> 'published'
OR published_at IS NOT NULL
);This constraint prevents an article from having a published status without a publication timestamp. It does not guarantee that the article is visible to the public at the right time, that its content is complete, or that its metadata is valid. Those rules belong in additional constraints, application validation, or the publication workflow, depending on their nature. Good schema design separates rules the database can enforce reliably from rules that require broader context.
Model Categories, Tags, and Relationships
Categories and tags are often confused because both help readers navigate content. Categories generally represent a controlled, relatively broad classification, such as Database Design, Web Architecture, or DevOps. Tags represent more specific concepts, such as PostgreSQL, indexing, caching, or TypeScript. This distinction is editorial rather than a database law, but defining it helps prevent the taxonomy from becoming a collection of overlapping labels.
If an article belongs to one category only, a category_id foreign key on the article table is sufficient. If articles can belong to several categories, a junction table is more appropriate. The schema should reflect the actual publishing requirements. Choosing many-to-many because it sounds flexible can be unnecessary; choosing one-to-many because it is simpler can become restrictive if multi-category publishing is already a requirement.
CREATE TABLE article_categories (
article_id bigint NOT NULL
REFERENCES articles(id) ON DELETE CASCADE,
category_id bigint NOT NULL
REFERENCES categories(id) ON DELETE RESTRICT,
is_primary boolean NOT NULL DEFAULT false,
PRIMARY KEY (article_id, category_id)
);
CREATE TABLE tags (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE,
slug text NOT NULL UNIQUE
);
CREATE TABLE article_tags (
article_id bigint NOT NULL
REFERENCES articles(id) ON DELETE CASCADE,
tag_id bigint NOT NULL
REFERENCES tags(id) ON DELETE RESTRICT,
PRIMARY KEY (article_id, tag_id)
);The composite primary keys prevent duplicate relationships. An article cannot be associated with the same category twice in articlecategories, and it cannot receive the same tag twice in articletags. The foreign keys prevent relationships from pointing to nonexistent records. The chosen deletion behavior is deliberate: deleting an article removes its junction records, while deleting a category or tag that is still referenced is restricted.
Deletion rules should reflect the product's behavior. Cascading from an article to its junction records is generally sensible because those associations have no independent meaning. Cascading from a category to articles would be a different and potentially destructive rule, so it should not be chosen casually. Foreign-key constraints protect the integrity of relationships, but they do not replace a deliberate content-retention policy.
Enforcing One Primary Category
If each article may have at most one primary category, PostgreSQL can enforce that requirement with a partial unique index. This is stronger than relying on a user interface to prevent multiple selections. The index does not require every article to have a primary category, however. If exactly one primary category is mandatory for every article, the design needs an additional enforcement strategy, such as a suitable transaction-safe workflow or a different schema.
CREATE UNIQUE INDEX one_primary_category_per_article
ON article_categories (article_id)
WHERE is_primary = true;This index prevents two category relationships for the same article from both being marked primary. A publishing service can still accidentally leave an article with no primary category, so it should validate that requirement when publishing. If concurrent operations can change primary categories, perform the changes in a transaction and handle constraint violations instead of assuming that separate application checks will always be safe.
Generate and Enforce Unique Slugs
A slug is the human-readable portion of a URL, such as postgresql-indexes-explained. It is commonly derived from a title, but the title and slug serve different purposes. Titles are editorial text that can be rewritten for clarity. Slugs are routing identifiers that may already be used in bookmarks, search results, shared links, and external references. Treating them as separate fields gives the application control over URL stability.
A typical slug-generation process lowercases the title, normalizes characters, replaces whitespace with hyphens, removes unsupported punctuation, and trims repeated or leading hyphens. For example, “Designing a Database-Driven Portfolio” could become designing-a-database-driven-portfolio. Transliteration rules, Unicode handling, and language support should be explicit decisions because not every title can be converted cleanly using the same rules.
export function slugify(title: string): string {
return title
.normalize("NFKD")
.replace(/\p{M}/gu, "")
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}This example creates lowercase ASCII slugs and removes combining marks after Unicode normalization. It is suitable for a simple English-oriented portfolio, but it is not a universal transliteration solution. Some scripts and characters do not map to ASCII equivalents under this process. A multilingual site should choose a deliberate URL policy and test it with real titles from the languages it supports.
Slug generation is not slug uniqueness. Two different articles can have the same title, and two different titles can normalize to the same slug. A uniqueness constraint in PostgreSQL is therefore essential. An application can propose a slug and check whether it already exists, but that check alone is not sufficient under concurrent writes: two requests could both observe that a slug is available before either inserts its record.
INSERT INTO articles (
title,
slug,
excerpt,
body
)
VALUES (
'Database Schema Design',
'database-schema-design',
'A practical guide to content modeling.',
'[]'::jsonb
)
ON CONFLICT (slug) DO NOTHING
RETURNING id, slug;The database's unique constraint is the final authority on whether a slug is available. ON CONFLICT DO NOTHING makes the example safe from a duplicate-slug insertion error, but it does not automatically generate an alternative slug. If the insert returns no row, the application must decide whether to retry with a suffix, ask the editor to choose a different slug, or report a conflict. The retry process must still rely on the database constraint.
Should Slugs Change When Titles Change?
Automatically regenerating a slug whenever a title changes can create broken inbound links. A safer default is to generate a slug when a record is created and then let the editor change it explicitly. If a published slug changes, the application should preserve a redirect from the old URL to the new one. For a small portfolio, a slug_redirects table can store the old slug, the target content record, and the creation timestamp.
Slug uniqueness must be defined within the correct namespace. If projects and articles live under separate route prefixes, such as /projects/example and /articles/example, the same slug can safely exist in both tables. If both content types share a common route namespace, a cross-table uniqueness rule is more complicated because a normal unique constraint cannot span two unrelated tables. A unified content table or a dedicated route registry may be appropriate when global uniqueness is a real requirement.
Validate Content at Multiple Layers
Validation should not be treated as a single function that runs only when an editor clicks Save. A robust content system validates data at multiple layers because each layer protects against a different class of failure. The user interface can provide immediate feedback, the application service can enforce domain rules, and PostgreSQL can protect persisted data against invalid writes from any path that reaches the database.
- Interface validation: Required fields, helpful messages, character limits, and immediate feedback.
- Application validation: Slug format, URL policy, publication requirements, content-block structure, and cross-field rules.
- Database constraints: NOT NULL, UNIQUE, CHECK, foreign keys, and primary keys.
- Workflow validation: Permissions, review status, publishing rules, and required editorial approval.
Consider a project record with a repository URL. The interface can explain that the field should contain a valid URL. The application can parse the value, restrict allowed protocols to HTTPS where appropriate, and reject malformed input. The database can enforce that a non-null value exists only where required, but comprehensive URL validation is usually better handled by application code. No single validation layer should be expected to solve every problem.
Content validation also needs to distinguish between syntactic validity and editorial quality. A title can be non-empty but still be unclear. An SEO description can fit within a character limit while failing to explain the article. A body can be valid JSON while containing an unsupported block type. Structural validation should verify the permitted block types and required properties, while editorial review should evaluate clarity, completeness, and usefulness.
Store SEO and Social Metadata Intentionally
SEO metadata belongs to the content record because it describes how that content should appear in search results and social previews. A portfolio article may need an SEO title and description distinct from its visible headline and excerpt. It may also need a social-sharing image and an optional canonical URL override. These fields should not be confused with the URL slug, which identifies the route, or the article body, which contains the actual content.
ALTER TABLE articles
ADD COLUMN seo_title text,
ADD COLUMN seo_description text,
ADD COLUMN social_title text,
ADD COLUMN social_description text,
ADD COLUMN social_image_url text,
ADD COLUMN canonical_url text,
ADD COLUMN noindex boolean NOT NULL DEFAULT false;Optional overrides are useful because not every article needs custom metadata. If seotitle is null, the application can fall back to the article's title. If socialdescription is null, it can use the excerpt. This approach avoids storing duplicate values merely because the interface expects a complete metadata object. However, fallback behavior should be implemented consistently so that different pages do not generate conflicting metadata.
A canonical URL override should be used only when a specific canonical destination is needed. For ordinary article pages, the application can derive the canonical URL from the configured site origin and the article route. Allowing arbitrary canonical URLs without validation can accidentally tell search engines that a page should be attributed to an unrelated destination. Drafts and private content should also be excluded from public queries independently of metadata settings.
Use Migrations to Evolve the Schema
A database schema is not finished after the first migration. New requirements emerge as the portfolio gains content and features. An article may need a reading time, a project may need a featured flag, or an existing field may need to be renamed. A migration records the intended change to the database schema so that development, staging, and production environments can move through the same sequence of changes.
Editing a production table manually and making the same change separately in development creates schema drift. One environment may contain a column that another lacks, causing a query to work locally and fail after deployment. Version-controlled migrations provide a repeatable history of schema changes and allow teams to review what a deployment will do. The migration tool can vary, but the underlying goal is consistent database structure across environments.
ALTER TABLE projects
ADD COLUMN is_featured boolean NOT NULL DEFAULT false;
CREATE INDEX projects_published_featured_idx
ON projects (published_at DESC)
WHERE status = 'published' AND is_featured = true;The example adds a Boolean field and creates a partial index for published featured projects. Whether the index is worthwhile depends on the query pattern, table size, and query plan. An index is not automatically beneficial simply because a field appears on a homepage. Indexes consume storage and add work to inserts and updates, so they should support measured or clearly expected access patterns.
For changes that affect existing records, plan the data migration as well as the schema migration. Adding a nullable column is often straightforward. Making that column mandatory may require backfilling existing rows, checking that every row has a valid value, and then adding the constraint. On a small portfolio, these operations may be manageable in one deployment. Larger systems may need an expand-and-contract approach that keeps old and new application versions compatible while the data is transformed.
Query and Render Content in the Application
A database-backed content model becomes useful when application queries match the way the content is presented. The homepage may need a small set of featured projects. An article archive may need published articles ordered by publication date. A category page may need all published articles associated with a specific category. These should be explicit queries that retrieve the required data, rather than loading every record and filtering it unnecessarily in application memory.
SELECT
id,
title,
slug,
excerpt,
published_at
FROM articles
WHERE status = 'published'
AND published_at <= now()
ORDER BY published_at DESC, id DESC
LIMIT 20;The query excludes drafts and future-scheduled articles, orders published content consistently, and limits the result set. Adding id as a secondary sort key gives the ordering a deterministic tie-breaker when multiple records share the same publication timestamp. For larger archives, cursor-based pagination may be preferable to large offsets. The appropriate method depends on how users navigate the archive and whether new content is published frequently.
In a Next.js application, the data-access layer should keep database queries separate from presentation components where practical. A page can retrieve a published article by slug, map the validated content blocks to supported rendering components, and generate metadata from the same record. This reduces the risk of the visible title, Open Graph title, and canonical URL being generated from inconsistent sources. Database credentials should remain server-side and must never be exposed in client bundles.
Caching introduces another design decision. A database-backed page does not have to query PostgreSQL on every request. Static generation, incremental regeneration, request-level caching, or server-side rendering can all be used depending on how frequently the content changes and how quickly updates must become visible. The important point is that a cache needs a freshness policy. Publishing or updating a record should invalidate or revalidate the relevant pages when immediate freshness is part of the product requirements.
Database-Backed CMS Versus Static Content
A database is not always the best storage option for a portfolio. Static Markdown or MDX files can be excellent for a small, developer-maintained publication. They are easy to version-control, review in pull requests, and deploy as part of the application. A relational database becomes more compelling when content needs to be edited through an interface, queried by category or tag, updated independently of deployments, or managed by multiple people.
| Dimension | Database-backed CMS | Static Markdown or MDX |
|---|---|---|
| Editing workflow | Can support an administrative editor | Usually involves editing files and deploying |
| Content changes | Can be published independently of code deployments | Commonly tied to a build or deployment |
| Relationships | Foreign keys and junction tables support explicit relationships | Relationships are usually represented in frontmatter or build-time logic |
| Validation | Application validation plus database constraints | Frontmatter schemas and build-time validation |
| Operational burden | Database, migrations, backups, permissions, and monitoring | Repository and build pipeline management |
| Query flexibility | Strong for filtering, relationships, and dynamic listings | Often sufficient for a small, predictable content collection |
| Version history | Requires an explicit content revision strategy | Git naturally tracks file changes |
| Failure modes | Database connectivity and availability become concerns | Content is unavailable if deployment or build artifacts are missing, though deployed pages can remain accessible |
| Best fit | Frequently updated or relational content | Small, mostly static developer publications |
The choice is not a contest in which the database-backed option is always more professional. If a developer publishes a few articles a month and is comfortable editing Markdown, a static content system may have lower operational cost and fewer moving parts. If the portfolio already has a database, a block editor, category management, or an administrative workflow, using PostgreSQL for content may simplify the overall system. The right architecture is the one that matches actual content operations.
A hybrid architecture is also viable. Project descriptions and articles can live in Markdown or MDX while user accounts, contact submissions, analytics, or other dynamic features use PostgreSQL. Alternatively, a database can remain the source of truth while published pages are statically generated or cached. Storage architecture and rendering architecture are separate decisions: choosing a database does not require rendering every page dynamically, and choosing static rendering does not require storing every source file in a particular format.
Common Database Design Mistakes
- Using titles as primary keys: Titles are editable and may not be unique.
- Generating slugs without a unique constraint: Concurrent writes can create conflicts even when the application checks availability.
- Duplicating content across pages: Independent copies drift and become inconsistent.
- Putting every relationship into a comma-separated field: This weakens referential integrity and complicates querying.
- Adding indexes without understanding query patterns: Extra indexes consume storage and increase write costs.
- Treating JSONB as schema-free magic: Structured content still needs validation and versioning.
- Changing published URLs without redirects: Existing links may break.
- Editing production schemas manually: Environments drift when changes are not captured in migrations.
- Publishing based only on a frontend flag: Public queries must enforce publication rules server-side.
- Overengineering the initial schema: Unneeded abstractions create more complexity than value.
One particularly common mistake is storing a category as plain text directly on each article. That approach is reasonable when categories are merely descriptive strings with no shared behavior. It becomes problematic when categories need their own slugs, descriptions, archive pages, or consistent renaming. A normalized category table allows one category record to be referenced by many articles, preventing spelling variations from silently becoming separate categories.
Another mistake is assuming that database constraints replace application design. A foreign key can ensure that a category exists, but it cannot decide whether the category is appropriate for an article. A unique constraint can prevent duplicate slugs, but it cannot select a good slug. A CHECK constraint can restrict a status to known values, but it cannot determine whether an editor has supplied a useful technical explanation. Integrity rules and editorial judgment solve different problems.
Test Integrity and Plan for Future Changes
Schema testing should cover more than whether the application can successfully insert a normal record. Test that duplicate slugs are rejected, nonexistent foreign keys fail, invalid status values are blocked, and publication rules behave as expected. Also test the publishing service when two requests attempt to claim the same slug. The expected result should be a controlled conflict or retry, not an unhandled database error or duplicate public route.
- Create a project and verify that its generated slug can be retrieved by the expected route.
- Insert two articles with the same slug and verify that the database rejects the duplicate.
- Attempt to associate an article with a nonexistent category and verify that the foreign key rejects it.
- Verify that draft and future-scheduled articles are excluded from public listings.
- Change a published slug and test the redirect from the old route.
- Apply migrations to a clean database and verify that the application starts successfully.
- Test backup restoration, not merely backup creation, when the database contains important content.
A backup is useful only if it can be restored within an acceptable period and produces a usable database. A small portfolio may not need elaborate disaster-recovery infrastructure, but it should still have a clear way to recover its content if the database or server is lost. Keep credentials outside source control, restrict database access, and avoid giving public-facing routes direct access to administrative operations. Security and recoverability are part of the data architecture, not unrelated deployment details.
Future changes should be driven by demonstrated requirements. If articles eventually need authors, introduce an authors table when author identity and profile data need to be managed independently. If content needs revision history, design an explicit revision model rather than assuming that updated_at preserves previous versions. If search becomes important, evaluate PostgreSQL full-text search or a dedicated search service based on actual needs. Each addition should solve a defined problem without making the current system harder to maintain unnecessarily.
Conclusion
A reliable database-driven portfolio starts with a clear content model. Projects, articles, categories, tags, slugs, and SEO metadata should each have an intentional role. Primary keys identify records, foreign keys protect relationships, unique constraints prevent duplicate identifiers, and migrations keep schema changes repeatable across environments. Application validation handles domain rules that database constraints alone cannot express, while careful query design ensures that public pages expose the right content.
The most important decision is not whether to use PostgreSQL or static files. It is whether the chosen content architecture matches the way the portfolio is maintained and published. Static content can be simpler and entirely sufficient for a small publication. A database-backed CMS can be more appropriate when content relationships, editorial workflows, and independent updates justify the additional operational responsibilities. Build the smallest model that reliably supports the requirements you actually have, then evolve it through explicit, tested migrations as those requirements change.
OPEN
Thoughts on the article.